PHP

Bulk INSERT in a Single Statement

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Insert a list of rows in one round trip by building a multi-VALUES statement with placeholders. Orders-of-magnitude faster than looping single INSERTs.
PHP
Raw
<?php
function bulkInsert(PDO $db, string $table, array $rows): int {
    if (!$rows) return 0;
    $cols    = array_keys($rows[0]);
    $colList = '`' . implode('`,`', $cols) . '`';
    $rowPh   = '(' . implode(',', array_fill(0, count($cols), '?')) . ')';
    $allPh   = implode(',', array_fill(0, count($rows), $rowPh));

    $sql = "INSERT INTO `$table` ($colList) VALUES $allPh";
    $params = [];
    foreach ($rows as $r) foreach ($cols as $c) $params[] = $r[$c] ?? null;
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    return $stmt->rowCount();
}

bulkInsert($db, 'events', [
    ['user_id'=>1,'event'=>'login'],
    ['user_id'=>2,'event'=>'signup'],
    ['user_id'=>1,'event'=>'view_page'],
]);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.