0

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?

3
  • This would be the perfect place to use a prepared statement and bound parameters. Commented Jun 3, 2013 at 14:09
  • define "best". Do you experience any problem with your current approach at the moment? Commented Jun 3, 2013 at 14:09
  • 1
    loop the array to create one multivalued INSERT statetment, example, INSERT INTO tableName VALUES (1, 'John'), (2, 'James') Commented Jun 3, 2013 at 14:11

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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();

1 Comment

Well, I am not fan of mysqli (most of the time I use PDO). The 's' means the first parameters is a string type. See: php.net/manual/en/mysqli-stmt.bind-param.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.