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

前端 未结 3 1474
忘掉有多难
忘掉有多难 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.

    0 讨论(0)
  • 2020-11-27 17:48

    2 solutions

    // multiple queries
    $stmt = $pdo->prepare('INSERT INTO table SET memberID=:memberID, programID=:programID, date_added=NOW()');
    $data = array(155, 165, 175, 185);
    foreach($data as $d) {
        $stmt->execute(array(':memberID' => $memberid, ':programID' => $d));
    }
    

    And

    // one query
    $data = array(155, 165, 175, 185);
    $values = array();
    foreach($data as $d) {
        $values[] = sprintf('(%d, %d, NOW())', $d, $memberid);
    }
    $sql = sprintf('INSERT INTO table (memberID, programID, date_added) VALUES %s', implode (', ', $values));
    $pdo->exec($sql);
    
    0 讨论(0)
  • 2020-11-27 17:59

    You could build the query programatically...:

    $sql = 'INSERT INTO table (memberID, programID) VALUES ';
    $insertQuery = array();
    $insertData = array();
    foreach ($data as $row) {
        $insertQuery[] = '(?, ?)';
        $insertData[] = $memberid;
        $insertData[] = $row;
    }
    
    if (!empty($insertQuery)) {
        $sql .= implode(', ', $insertQuery);
        $stmt = $db->prepare($sql);
        $stmt->execute($insertData);
    }
    
    0 讨论(0)
提交回复
热议问题