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.<
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.
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);
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);
}