Skip to content

Instantly share code, notes, and snippets.

@Chizaram-Igolo
Forked from gskema/db.php
Created November 2, 2022 19:22
Show Gist options
  • Save Chizaram-Igolo/f751082ac59911b860661c7bd53a4d6f to your computer and use it in GitHub Desktop.
Save Chizaram-Igolo/f751082ac59911b860661c7bd53a4d6f to your computer and use it in GitHub Desktop.
PHP PDO bulk INSERT
<?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