Insert multiple rows with PDO prepared statements

后端 未结 4 1650
春和景丽
春和景丽 2020-11-28 12:08

I would like to know if it is possible to insert multiple rows using one prepared statement. Below is an example of how I would normally insert one row into the db:

4条回答
  •  有刺的猬
    2020-11-28 12:38

    To keep your code, you have to make a loop for executing all insertions you need :

    $array_params = array();
    $params[':val1']="val1 1";
    $params[':val2']="val1 2";
    $params[':val3']="val1 3";
    $array_params[] = $params;
    
    $params[':val1']="val2 1";
    $params[':val2']="val2 2";
    $params[':val3']="val2 3";
    $array_params[] = $params;
    
    $sql="INSERT INTO table (col1,col2,col3) VALUES (:val1,:val2,:val3)";
    $stmt=DB::getInstance()->prepare($sql);
    foreach($array_params as $params)
    {
      $stmt->execute($params);
    }
    

    But its possible to execute multiple insertions with one query like INSERT INTO table (col1,col2,col3) VALUES ("val1","val2","val3"),("val4","val5","val6"),("val7","val8,"val9"), by using something like this to build the query:

    $all_inserts = array( array('val1', 'val2', 'val3'),array('val4', 'val5', 'val6'));
    $sql = 'INSERT INTO table (col1,col2,col3) VALUES ';
    $rows = array();
    foreach ($all_inserts as $one_insert)
    {
       $rows[] = '('.implode(',', $pdo->quote($one_insert).')';
    }
    $sql .= ' '.implode(',', $rows);
    $pdo->query($sql); 
    

提交回复
热议问题