0

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 2

2

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')
");
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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.