Last active
September 19, 2022 18:49
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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