Created
September 1, 2015 11:15
-
-
Save gskema/7a7c0eec2a7b97b4b03a to your computer and use it in GitHub Desktop.
PHP PDO bulk INSERT
This file contains hidden or 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
array_merge is very slow when doing it on large queries (10000 rows for example) but you can refactor it to be:
its very fast compared to array_merge on each rows.