Jump to content

Hello, I'm trying to insert an array into mySql database but it keeps inserting the entire array in a single field.

 

 

//the $authors variable is an array taken from an exploded string$authors = [];if(isset($_POST['blogAuthors'])){$authors = explode('\n', $_POST['blogAuthors']);} foreach($authors as $author){            $sql = "INSERT INTO authors (authorName, authorWorkHash) VALUES (:author, :hash)";            $query = $db->prepare($sql);            $query->execute(array(':author'=>$author,':hash'=>$blogHash));        }

 

the database keeps inserting the author names as one record instead of a separate record for each person. Any help would be appreciated. Thanks.

Edited by colonel_mortis
Code tags

My system: CPU: Intel i5 6500; Mobo: H110M-k; GPU: Nvidia GT 730; Memory: 16 GB; HDD: 2x 1TB HDD;

Link to comment
https://linustechtips.com/topic/527676-need-help-with-mysql-array-insertion/
Share on other sites

Link to post
Share on other sites

I'm not sure if these are the codes you're looking for but this is from phpmyadmin from the SQL tab:

INSERT INTO `authors`(`authorID`, `authorName`, `authorWorkHash`) VALUES ([value-1],[value-2],[value-3])
SELECT `authorID`, `authorName`, `authorWorkHash` FROM `authors` WHERE 1
UPDATE `authors` SET `authorID`=[value-1],`authorName`=[value-2],`authorWorkHash`=[value-3] WHERE 1
DELETE FROM `authors` WHERE 1

My system: CPU: Intel i5 6500; Mobo: H110M-k; GPU: Nvidia GT 730; Memory: 16 GB; HDD: 2x 1TB HDD;

Link to post
Share on other sites

So as it turns out the explode function isn't really splitting the string. I'll look into it. Thanks for your help.

Isn't really related to your main question, but you could use a ternary statement to achieve the same thing your first two lines do.

 

$authors = (isset($_POST['blogAuthors'])) ? explode('\n', $_POST['blogAuthors']) : null;

15" MBP TB

AMD 5800X | Gigabyte Aorus Master | EVGA 2060 KO Ultra | Define 7 || Blade Server: Intel 3570k | GD65 | Corsair C70 | 13TB

Link to post
Share on other sites

Unrelated to your original question, but the original purpose of prepared statements was to allow repeated queries to run faster, which you should probably take advantage of. Rather than preparing the statement every time in the loop, just prepare it once, outside, then use the prepared statement inside:

$sql = "INSERT INTO authors (authorName, authorWorkHash) VALUES (:author, :hash)";$query = $db->prepare($sql);foreach($authors as $author){            $query->execute(array(':author'=>$author,':hash'=>$blogHash));}

HTTP/2 203

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×