Skip to content

Instantly share code, notes, and snippets.

@rxnlabs
Last active September 19, 2022 18:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rxnlabs/c5f6dde0f42b260b208a to your computer and use it in GitHub Desktop.
Save rxnlabs/c5f6dde0f42b260b208a to your computer and use it in GitHub Desktop.
PHP - Insert multiple rows into MySQL table using a single query statement. Example based on code from https://phpacademy.org/topics/how-to-insert-multiple-rows-in-mysql-in-one-query-using-pdo-from-a-form/34096
<?php
// https://phpacademy.org/topics/how-to-insert-multiple-rows-in-mysql-in-one-query-using-pdo-from-a-form/34096
function placeholder( $text, $count = 0, $separator = ',' ) {
$result = array();
if ($count > 0) {
for ($x = 0; $x < $count; $x++) {
$result[] = $text;
}
}
return implode( $separator, $result );
}
$pdo = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$datafields = array( 'student_name' => '', 'roll_no' => '', 'subject' => '' );
$data[] = array( 'student_name' => 'John Doe', 'roll_no' => 'CC0801', 'subject' => 'Computer Networks' );
$data[] = array( 'student_name' => 'Jane Doe', 'roll_no' => 'CC0802', 'subject' => 'Computer Networks' );
$data[] = array( 'student_name' => 'Summer Doe', 'roll_no' => 'CC0803', 'subject' => 'Computer Networks' );
$pdo->beginTransaction(); // Speed up your inserts
$insertvalues = array();
foreach ($data as $d) {
$questionmarks[] = '(' . placeholder( '?', sizeof($d)) . ')';
$insertvalues = array_merge( $insertvalues, array_values($d) );
}
$sql = "INSERT INTO table (" . implode( ',', array_keys( $datafields ) ) . ") VALUES " . implode( ',', $questionmarks);
$statement = $pdo->prepare($sql);
try {
$statement->execute($insertvalues);
} catch(PDOException $e) {
echo $e->getMessage();
}
$pdo->commit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment