I want to add a bunch of people to a table at the same time. Is there a way to do a batch insert perhaps as an array or do I need to use a loop as in for each...mysql_query(Insert into people (name,address,email) values ('$name','$adr','$email')). Many thanks!
2 Answers
You can use this format :
"INSERT INTO table (id,value) VALUES (1,'temp1'),(2,'temp2'),(3,'temp3')"
So as per your query:
mysql_query("insert into people (name,address,email)
values ('$name1','$adr1','$email1'),
values ('$name2','$adr2','$email2'),
values ('$name3','$adr3','$email3'),
values ('$name4','$adr4','$email4')
");
1 Comment
josmith
Please remember to use mysql_real_escape_string() to escape to make sure you are secure against SQL Injection. And even better use, prepared statements.
INSERT INTO people (name, address,email)
VALUES ('$name','$adr','$email'),
('$name2','$adr2','$email2'),
('$name3','$adr3','$email3')
As for the implementation of the query, I'd go away from the mysql_ functions since the docs clearly state that for newer versions of MySql which you are likely to be using, you should use mysqli instead.
If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use the mysqli extension instead.
Sample of usage:
mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo $mysqli->connect_error;
}else{
$mysqli->query("INSERT INTO people (name, address,email)
VALUES ('$name','$adr','$email'),
('$name2','$adr2','$email2'),
('$name3','$adr3','$email3')");
}