Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple mysql INSERT statements in one query php [duplicate]

Tags:

php

mysql

Is this legal?

$string1= "INSERT INTO....;"; $string1 .= "INSERT INTO....;"; $string1 .= "INSERT INTO....;"; mysql_query($string1) or die(mysql_error());  
like image 462
Ian McCullough Avatar asked Aug 20 '09 17:08

Ian McCullough


People also ask

How do I run multiple inserts in MySQL?

MySQL INSERT multiple rows statement In this syntax: First, specify the name of table that you want to insert after the INSERT INTO keywords. Second, specify a comma-separated column list inside parentheses after the table name. Third, specify a comma-separated list of row data in the VALUES clause.

How to use ON DUPLICATE KEY UPDATE in MySQL?

ON DUPLICATE KEY UPDATE is a MariaDB/MySQL extension to the INSERT statement that, if it finds a duplicate unique or primary key, will instead perform an UPDATE. The row/s affected value is reported as 1 if a row is inserted, and 2 if a row is updated, unless the API's CLIENT_FOUND_ROWS flag is set.

Can we insert multiple rows single insert statement?

Answer. Yes, instead of inserting each row in a separate INSERT statement, you can actually insert multiple rows in a single statement. To do this, you can list the values for each row separated by commas, following the VALUES clause of the statement.


2 Answers

For what it's worth, and depending on if you're inserting the same data into the same tables, it's much better to insert multiple values with the one insert e.g.

INSERT INTO a VALUES (1,23),(2,34),(4,33); INSERT INTO a VALUES (8,26),(6,29); 
like image 127
Gavin Gilmour Avatar answered Sep 20 '22 16:09

Gavin Gilmour


No, mysql_query() only allows one query at a time.

You can insert multiple rows like this:

INSERT INTO table (col1, col2) VALUES (1, 2), (3, 4), (5, 6) 
like image 35
Greg Avatar answered Sep 20 '22 16:09

Greg