What is the best way to insert multiple rows in PHP PDO MYSQL?

后端 未结 4 1672
清歌不尽
清歌不尽 2020-12-03 21:14

Say, we have multiple rows to be inserted in a table:

$rows = [(1,2,3), (4,5,6), (7,8,9) ... ] //[ array of values ];

Using PDO:

         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-03 21:53

    You have at least these two options:

    $rows = [(1,2,3), (4,5,6), (7,8,9) ... ];
    
    $sql = "insert into `table_name` (col1, col2, col3) values (?,?,?)";
    
    $stmt = $db->prepare($sql);
    
    foreach($rows as $row)
    {
        $stmt->execute($row);
    }
    
    OR:
    
    $rows = [(1,2,3), (4,5,6), (7,8,9) ... ];
    
    $sql = "insert into `table_name` (col1, col2, col3) values ";
    
    $paramArray = array();
    
    $sqlArray = array();
    
    foreach($rows as $row)
    {
        $sqlArray[] = '(' . implode(',', array_fill(0, count($row), '?')) . ')';
    
        foreach($row as $element)
        {
            $paramArray[] = $element;
        }
    }
    
    // $sqlArray will look like: ["(?,?,?)", "(?,?,?)", ... ]
    
    // Your $paramArray will basically be a flattened version of $rows.
    
    $sql .= implode(',', $sqlArray);
    
    $stmt = $db->prepare($sql);
    
    $stmt->execute($paramArray);
    

    As you can see the first version features a lot simpler code; however the second version does execute a batch insert. The batch insert should be faster, but I agree with @BillKarwin that the performance difference will not be noticed in the vast majority of implementations.

提交回复
热议问题