PDO MySQL: Insert multiple rows in one query

后端 未结 1 1575
北恋
北恋 2020-11-27 19:27

Hello I am making a class for doing multiple insert in pdo.

It is something like this

INSERT INTO $table (key1,key2,key3,etc) VALUE (value1,value2,va         


        
相关标签:
1条回答
  • 2020-11-27 19:42

    An easy way for this avoiding the complications would be something like this

    $stmt = $pdo->prepare('INSERT INTO foo VALUES(:a, :b, :c)');
    foreach($data as $item)
    {
        $stmt->bindValue(':a', $item[0]);
        $stmt->bindValue(':b', $item[1]);
        $stmt->bindValue(':c', $item[2]);
        $stmt->execute();
    }
    

    However, this executes the statement multiple times. So, it is better if we create a long single query in order to do this.

    Here is an example of how we can do this.

    $query = "INSERT INTO foo (key1, key2) VALUES "; //Prequery
    $qPart = array_fill(0, count($data), "(?, ?)");
    $query .=  implode(",",$qPart);
    $stmt = $dbh -> prepare($query); 
    $i = 1;
    foreach($data as $item) { //bind the values one by one
       $stmt->bindValue($i++, $item['key1']);
       $stmt->bindValue($i++, $item['key2']);
    }
    $stmt -> execute(); //execute
    
    0 讨论(0)
提交回复
热议问题