PDO Prepared Inserts multiple rows in single query

后端 未结 22 2651
感情败类
感情败类 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:09

    Two possible approaches:

    $stmt = $pdo->prepare('INSERT INTO foo VALUES(:v1_1, :v1_2, :v1_3),
        (:v2_1, :v2_2, :v2_3),
        (:v2_1, :v2_2, :v2_3)');
    $stmt->bindValue(':v1_1', $data[0][0]);
    $stmt->bindValue(':v1_2', $data[0][1]);
    $stmt->bindValue(':v1_3', $data[0][2]);
    // etc...
    $stmt->execute();
    

    Or:

    $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();
    }
    

    If the data for all the rows are in a single array, I would use the second solution.

提交回复
热议问题