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.
For example:
I want to enroll in programid 155, 165, 175, and 185.
My array is set up as simple as:
$data = array();
$data[] = 155;
$data[] = 165;
$data[] = 175;
$data[] = 185;
When it comes time to insert this information into the associated table, I also include additional elements from the other part of the enrollment:
For example, if I were doing a SINGLE program insert statement, it would look as follows:
$stmt = $db->prepare("INSERT INTO table SET memberID=?, programID=?, date_added=NOW()");
$stmt->execute(array($memberid, 155));
I would normally create a simple loop for the array above which would call multiple instances of the sql statement and execute such as:
for($j = 0; $j < (count($data)-1); $j++) {
$stmt = $db->prepare("INSERT INTO table SET memberID=?, programID=?, date_added=NOW()");
$stmt->execute(array($memberid, $data[$j]));
}
I do realize the code above is invalid ( $data[$j] ) but looking for the right way to do the call.
I have also been told before that building a single dynamic sql statement is overall better than multiple calls like above. My first pass would be something like:
$sql = array();
foreach( $data as $row ) {
$sql[] = '("'.$memberid.'", "'.$row[$j].'", NOW()")';
}
mysql_real_query('INSERT INTO table (memberid, programid) VALUES '.implode(',', $sql));
but with PDO I am not quite sure how this works, especially with placeholders (?).
Any suggestions?