Insert multiple rows with PDO prepared statements

后端 未结 4 1690
春和景丽
春和景丽 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条回答
  •  天涯浪人
    2020-11-28 12:38

    If you're only inserting a few hundred rows, I'd favor simpler code like the following. Prepare a single-row INSERT statement, and then loop over your data array, executing the prepared query once for each row.

    $rows = array(
                  array('abc', 'def', 'ghi'), // row 1 to insert
                  array('abc', 'def', 'ghi'), // row 2 to insert
                  array('abc', 'def', 'ghi')  // row 3 to insert
                  // and so on ...
    );
    
    $params = implode(",", array_fill(0, count($rows[0]), "?"));
    
    $sql = "INSERT INTO mytable VALUES ($params)";
    
    $stmt = $pdo->prepare($sql); // rely on exceptions for error detection
    
    foreach ($rows as $row) {
        $stmt->execute($row);
    }
    

    MySQL does support multi-row INSERT syntax of course, so you could try putting that together.

    $params = implode(",", array_fill(0, count($rows[0]), "?"));
    
    $tuples = "(" . implode("),(", array_fill(0, count($rows), $params)) . ")";
    
    $sql = "INSERT INTO mytable VALUES $tuples";
    
    $values = call_user_func_array("array_merge", $rows);
    
    $stmt = $pdo->prepare($sql);
    
    $stmt->execute($values);
    

    But if you try to create a single INSERT statement with as many tuples as the items in your data array, you might accidentally generate an SQL statement that is longer than the maximum packet length.

    If you have thousands of rows, enough so that executing a prepared statement one row at a time is too much overhead, you should use LOAD DATA INFILE.

提交回复
热议问题