Multiple MySQL Insert Statements in One Query PHP

Multiple mysql INSERT statements in one query php

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);

How to run multiple insert query in SQL using PHP in one go?


The problem is, I need to insert data to first table and if its successfully inserted then only run query for the second table.

This means you need a transaction.

A transaction is a set of queries that either all execute ok or if one fails - they all fail. This is to ensure you don't end up with crap data in your tables.

Do not

  • Do not use multiquery.
  • Do not use mysql_* function(s).
  • Do not use bulk inserts.

People telling you to do that just have absolutely no clue what they're doing, ignore them.

Do

  • Use PDO
  • Use prepared statements
  • Prepare the statement(s) ONCE, use them MULTIPLE times

Sample code - do NOT copy paste

$dsn = 'mysql:dbname=testdb;host=127.0.0.1;charset=utf8mb4';
$user = 'dbuser';
$password = 'dbpass';

$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$insert['first'] = $pdo->prepare("INSERT INTO table SET col1 = :val, col2 = :val2");
$insert['second'] = $pdo->prepare("INSERT INTO another_table SET col1 = :val, col2 = :val2");

$pdo->beginTransaction();

$insert['first']->bindValue(':val', 'your value');
$insert['first']->bindValue(':val2', 'anothervalue');
$insert['first']->execute();

$insert['second']->bindValue(':val', 'your value');
$insert['second']->bindValue(':val2', 'anothervalue');
$insert['second']->execute();

$pdo->commit();

The code above will save the data in two tables ONLY if both inserts are successful.

How do you execute multiple sql insert statements in one php page

Your code is close to correct. I tweaked it a bit.

// establish DB connection (this includes creates $conn variable)

$conn = mysqli_connect("127.0.0.1", "app", "aaaa", "sss");
if ( ! $conn ) {
throw new Exception('Connection failed');
}

$userId = 123;
$supplierId = 200;
$order_items = [
['prodId' => 2000, 'qty' => 5, 'costPrice' => 1.25],
['prodId' => 2001, 'qty' => 7, 'costPrice' => 2.25],
['prodId' => 2002, 'qty' => 9, 'costPrice' => 1.20],
['prodId' => 2003, 'qty' => 15, 'costPrice' => 3.25],
['prodId' => 2004, 'qty' => 25, 'costPrice' => 5.22],
['prodId' => 2005, 'qty' => 35, 'costPrice' => 5.25],
['prodId' => 2006, 'qty' => 45, 'costPrice' => 11.51],
];

// create PO record
$sql = "INSERT INTO purchaseorders (PODate, supplierId, userId) VALUES (?,?,?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
// header("Location: ../place.php?error=sqlerror");
throw new Exception("SQL error! " . mysqli_error($conn));
}
else {
$date = date('Y-m-d H:i:s');
mysqli_stmt_bind_param($stmt, "sss", $date, $supplierId, $userId);
mysqli_stmt_execute($stmt);
}

// // get last PO record id
$POId = mysqli_insert_id($conn);
echo "POId = " . print_r($POId, true) . "\n";

$sql1 = "INSERT INTO podetails (PONumber, productId, poquantity,
pocostPrice, delivered, paidStatus) VALUES
(?,?,?,?,?,?);";
$stmt1 = mysqli_stmt_init($conn);
if (!$stmt1) {
throw new Exception("SQl Connect error! " . mysqli_error($conn));
}

if (!mysqli_stmt_prepare($stmt1, $sql1)) {
throw new Exception("SQl Connect error! " . mysqli_error($conn));
}
// for each record in grid - create PO details record
foreach ($order_items as $item) {
$delivered = "false";
$paidStatus = "false";
if ( ! mysqli_stmt_bind_param($stmt1, "ssssss", $POId,
$item['prodId'], $item['qty'], $item['costPrice'], $delivered, $paidStatus) ) {
throw new Exception("SQl error! " . mysqli_error($conn));
}
if( ! mysqli_stmt_execute($stmt1) ) {
throw new Exception("SQl error! " . mysqli_error($conn));
}
}

echo "PO Placed: PO Number = ".$POId . "\n";

I made these tables to run it locally.

CREATE TABLE `purchaseorders` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`PODate` date DEFAULT NULL,
`supplierId` int(10) unsigned DEFAULT NULL,
`userId` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

CREATE TABLE `podetails` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`PONumber` int(10) unsigned DEFAULT NULL,
`productId` int(10) unsigned DEFAULT NULL,
`poquantity` int(11) DEFAULT NULL,
`pocostPrice` decimal(9,2) DEFAULT NULL,
`delivered` varchar(20) NOT NULL DEFAULT 'false',
`paidStatus` varchar(20) NOT NULL DEFAULT 'false',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;

Mysql multiple insert query

From documentation

Inserting NULL into a column that has been declared NOT NULL. For
multiple-row INSERT statements or INSERT INTO ... SELECT statements,
the column is set to the implicit default value for the column data
type. This is 0 for numeric types, the empty string ('') for string
types, and the “zero” value for date and time types. INSERT INTO ...
SELECT statements are handled the same way as multiple-row inserts
because the server does not examine the result set from the SELECT to
see whether it returns a single row. (For a single-row INSERT, no
warning occurs when NULL is inserted into a NOT NULL column. Instead,
the statement fails with an error.)

Merge multiple foreach MySQL insert statements into one with PHP array data

You can't really combine it into one query using UPDATE, as the value and condition come in pairs (the value and condition is different for each row you are updating).

There is a hacky fix with INSERT INTO..ON DUPLICATE KEY UPDATE, but I would refrain from using that - see the question linked by RiggsFolly in the comments.

When using a prepared statement, you can execute the same query multiple times (you would have to query it multiple times anyways, even with mysqli_query(), but this is optimized and more secure when using a prepared statement).

$sql = "UPDATE images SET order_id=? WHERE id=?";
$stmt = $connection->prepare($sql);
foreach($array as $key=>$item){
$stmt->bind_param("ss", $item['order_id'], $item['id']);
$stmt->execute();
}
$stmt->close();

If your IDs are integers instead of strings, replace the respective s with an i.

  • PHP.net on mysqli::prepare()
  • PHP.net on mysqli-stmt::bind_param()
  • PHP.net on mysqli-stmt::execute()

Insert multiple rows with one query MySQL


 INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);

http://dev.mysql.com/doc/refman/5.5/en/insert.html

PDO MySQL: Insert multiple rows in one query

An easy way for this avoiding the complications would be something like this

$stmt = $pdo->prepare('INSERT INTO foo VALUES(:a, :b, :c)');
foreach($data as $item)
{
$stmt->bindValue(':a', $item[0]);
$stmt->bindValue(':b', $item[1]);
$stmt->bindValue(':c', $item[2]);
$stmt->execute();
}

However, this executes the statement multiple times. So, it is better if we create a long single query in order to do this.

Here is an example of how we can do this.

$query = "INSERT INTO foo (key1, key2) VALUES "; //Prequery
$qPart = array_fill(0, count($data), "(?, ?)");
$query .= implode(",",$qPart);
$stmt = $dbh -> prepare($query);
$i = 1;
foreach($data as $item) { //bind the values one by one
$stmt->bindValue($i++, $item['key1']);
$stmt->bindValue($i++, $item['key2']);
}
$stmt -> execute(); //execute


Related Topics



Leave a reply



Submit