How to insert an array into a single MySQL Prepared statement w/ PHP and PDO

前端 未结 3 1491
忘掉有多难
忘掉有多难 2020-11-27 16:55

During an online enrollment, a customer may select a number of programs which they choose to enroll for. These programs are three digit integers and are stored in an array.<

3条回答
  •  醉话见心
    2020-11-27 17:40

    What you are looking for is how to do a BULK insert, this is more SQL related than to PDO itself.

    You only have to do the exact same thing than with *_query, build your bulk insert query and your param array side by side.

    $placeholder = array();
    $values = "?, ?, ?, ...";
    $args = array();
    foreach ($arrays as $array) {
      $placeholder[] = $value;
      $args[] = $array['col1'];
      $args[] = $array['col2'];
      $args[] = $array['col3'];
      ...
    }    
    $sql = "INSERT INTO table (col1, col2, ... ) VALUES ("
         . implode('), (', $placeholder)
         . ")"; 
    $stmt = $db->prepare($sql);
    $db->execute($sql, $args);
    

    This is an ugly but working algorithm, I think.

提交回复
热议问题