PDO Prepared Inserts multiple rows in single query

后端 未结 22 2069
感情败类
感情败类 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-22 00:05

    The Accepted Answer by Herbert Balagtas works well when the $data array is small. With larger $data arrays the array_merge function becomes prohibitively slow. My test file to create the $data array has 28 cols and is about 80,000 lines. The final script took 41s to complete.

    Using array_push() to create $insert_values instead of array_merge() resulted in a 100X speed up with execution time of 0.41s.

    The problematic array_merge():

    $insert_values = array();
    
    foreach($data as $d){
     $question_marks[] = '('  . placeholders('?', sizeof($d)) . ')';
     $insert_values = array_merge($insert_values, array_values($d));
    }
    

    To eliminate the need for array_merge(), you can build the following two arrays instead:

    //Note that these fields are empty, but the field count should match the fields in $datafields.
    $data[] = array('','','','',... n ); 
    
    //getting rid of array_merge()
    array_push($insert_values, $value1, $value2, $value3 ... n ); 
    

    These arrays can then be used as follows:

    function placeholders($text, $count=0, $separator=","){
        $result = array();
        if($count > 0){
            for($x=0; $x<$count; $x++){
                $result[] = $text;
            }
        }
    
        return implode($separator, $result);
    }
    
    $pdo->beginTransaction();
    
    foreach($data as $d){
     $question_marks[] = '('  . placeholders('?', sizeof($d)) . ')';
    }
    
    $sql = "INSERT INTO table (" . implode(",", array_keys($datafield) ) . ") VALUES " . implode(',', $question_marks);
    
    $stmt = $pdo->prepare ($sql);
    try {
        $stmt->execute($insert_values);
    } catch (PDOException $e){
        echo $e->getMessage();
    }
    $pdo->commit();
    

提交回复
热议问题