简体   繁体   中英

PHP/MYSQL Add batch of records

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!

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')
");
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.

The manual for mysqli

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')");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM