Insert multiple rows with PDO prepared statements

后端 未结 4 1689
春和景丽
春和景丽 2020-11-28 12:08

I would like to know if it is possible to insert multiple rows using one prepared statement. Below is an example of how I would normally insert one row into the db:

4条回答
  •  旧时难觅i
    2020-11-28 12:49

    If your table is transactional (for example an InnoDB), you can use a Transaction to speed up your insertions. A transaction has also the advantage of roll backs.

    $pdo = DB::getInstance();
    $stmt = $pdo->prepare('INSERT INTO table VALUES (col1, col2, col3) VALUES (:val1, :val2, :val3)');
    
    $pdo->beginTransaction();
    
    // The queries are not executed yet, but pushed to a transaction "stack"
    foreach ($values as $value) {
        $stmt->execute([
            ':val1' => $value['val1'],
            ':val2' => $value['val2'],
            ':val3' => $value['val3'],
        ]);
    }
    
    // Executes all the queries "at once"
    $pdo->commit();
    

提交回复
热议问题