1

how to add multiple records in mysql using php. Is using array the only solution to this problem. Because I tried using array but the record that would be added in the database would look like this: array

1
  • 1
    Can you provide more details and your code source ? Commented Jan 23, 2010 at 13:56

2 Answers 2

4

You can use a multivalue insert statement (INSERT... VALUES (record1), (record2) etc) (see http://dev.mysql.com/doc/refman/5.1/en/insert.html)

This is how you can construct such a statement from array of records

$values = array();
foreach($records_array as $record)
    $values[] = sprintf("( '%s' , '%s' )", addslashes($record['name']), addslashes($record['email']));
$sql = "INSERT INTO users(name, email) VALUES " . implode(",", $values);
mysql_query($sql);
Sign up to request clarification or add additional context in comments.

2 Comments

A good post but NOTE: use mysql_real_escape_string instead of addslashes!!!!!!! php.net/manual/en/function.mysql-real-escape-string.php
it stands for string replace of the params addslashes($record['name']) supplied
3

You need to go through each member of the array:

foreach($array as $record)
 {   ...  }

and perform an INSERT query for each member or - better for performance - insert all records in one statement as outlined in user187291's answer.

2 Comments

It would be better to perform it all as one query instead of having to hit the DB for each iteration. No?
True. @stereofrog's answer outlines how. I didn't know VALUES can do multiple rows at once!

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.