Reputation: 1765
I have an array of names. My table structure is:
id | name
What would be the best way to insert each name from the array in to a separate row in the table?
id | name
1 | John
2 | James
I was thinking about looping through the array in PHP bu there must be a better way?
Upvotes: 0
Views: 885
Reputation: 11181
A small improvement to @Daryl Gill for prepare
better practice
// List of names to insert
$names = array("Daryl", "AnotherName");
// Prepare once
$sh = $db->prepare("INSERT INTO tblname (Name) VALUES (?)");
foreach ($names AS $name){
$sh->bind_param('s', $name);
$sh->execute();
}
// Free resource when we're done
$sh->close();
Upvotes: 0
Reputation: 5524
Using MySQli For Example:
$DB = new mysqli ("Server","username","password","database");
$Array = array("Daryl", "AnotherName");
foreach ($Array AS $Names){
$Query = $DB->prepare("INSERT INTO Table (Name) VALUES (?)");
$Query->bind_param('s',$Names);
$Query->execute();
$Query->close();
}
Best possible way would be to loop through the array using a foreach to get the individual values.. Then perform an insert on the current value before looping to the next.
Upvotes: 3