PDO Prepared Inserts multiple rows in single query

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

    Here is another (slim) solution for this issue:

    At first you need to count the data of the source array (here: $aData) with count(). Then you use array_fill() and generate a new array wich as many entries as the source array has, each with the value "(?,?)" (the number of placeholders depends on the fields you use; here: 2). Then the generated array needs to be imploded and as glue a comma is used. Within the foreach loop, you need to generate another index regarding on the number of placeholders you use (number of placeholders * current array index + 1). You need to add 1 to the generated index after each binded value.

    $do = $db->prepare("INSERT INTO table (id, name) VALUES ".implode(',', array_fill(0, count($aData), '(?,?)')));
    
    foreach($aData as $iIndex => $aValues){
     $iRealIndex = 2 * $iIndex + 1;
     $do->bindValue($iRealIndex, $aValues['id'], PDO::PARAM_INT);
     $iRealIndex = $iRealIndex + 1;
     $do->bindValue($iRealIndex, $aValues['name'], PDO::PARAM_STR);
    }
    
    $do->execute();
    

提交回复
热议问题