-
-
Save Chizaram-Igolo/f751082ac59911b860661c7bd53a4d6f to your computer and use it in GitHub Desktop.
PHP PDO bulk INSERT
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 | |
class Db | |
{ | |
public function batchInsert($table, array $rows, array $columns = array()) | |
{ | |
// Is array empty? Nothing to insert! | |
if (empty($rows)) { | |
return true; | |
} | |
// Get the column count. Are we inserting all columns or just the specific columns? | |
$columnCount = !empty($columns) ? count($columns) : count(reset($rows)); | |
// Build the column list | |
$columnList = !empty($columns) ? '('.implode(', ', $columns).')' : ''; | |
// Build value placeholders for single row | |
$rowPlaceholder = ' ('.implode(', ', array_fill(1, $columnCount, '?')).')'; | |
// Build the whole prepared query | |
$query = sprintf( | |
'INSERT INTO %s%s VALUES %s', | |
$table, | |
$columnList, | |
implode(', ', array_fill(1, count($rows), $rowPlaceholder)) | |
); | |
// Prepare PDO statement | |
$statement = $this->connection->prepare($query); | |
// Flatten the value array (we are using ? placeholders) | |
$data = array(); | |
foreach ($rows as $rowData) { | |
$data = array_merge($data, array_values($rowData)); | |
} | |
// Did the insert go successfully? | |
return $statement->execute($data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment