PDO Prepared Inserts multiple rows in single query

后端 未结 22 2043
感情败类
感情败类 2020-11-21 23:38

I am currently using this type of SQL on MySQL to insert multiple rows of values in one single query:

INSERT INTO `tbl` (`key1`,`key2`) VALUES (\'r1v1\',\'r1         


        
22条回答
  •  伪装坚强ぢ
    2020-11-21 23:51

    Most of the solutions given here to create the prepared query are more complex that they need to be. Using PHP's built in functions you can easily creare the SQL statement without significant overhead.

    Given $records, an array of records where each record is itself an indexed array (in the form of field => value), the following function will insert the records into the given table $table, on a PDO connection $connection, using only a single prepared statement. Note that this is a PHP 5.6+ solution because of the use of argument unpacking in the call to array_push:

    private function import(PDO $connection, $table, array $records)
    {
        $fields = array_keys($records[0]);
        $placeHolders = substr(str_repeat(',?', count($fields)), 1);
        $values = [];
        foreach ($records as $record) {
            array_push($values, ...array_values($record));
        }
    
        $query = 'INSERT INTO ' . $table . ' (';
        $query .= implode(',', $fields);
        $query .= ') VALUES (';
        $query .= implode('),(', array_fill(0, count($records), $placeHolders));
        $query .= ')';
    
        $statement = $connection->prepare($query);
        $statement->execute($values);
    }
    

提交回复
热议问题