Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to insert an array into a single MySQL Prepared statement w/ PHP and PDO
    primarykey
    data
    text
    <p>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.</p> <p>For example:</p> <p>I want to enroll in programid 155, 165, 175, and 185.</p> <p>My array is set up as simple as:</p> <pre><code>$data = array(); $data[] = 155; $data[] = 165; $data[] = 175; $data[] = 185; </code></pre> <p>When it comes time to insert this information into the associated table, I also include additional elements from the other part of the enrollment:</p> <p>For example, if I were doing a SINGLE program insert statement, it would look as follows:</p> <pre><code>$stmt = $db-&gt;prepare("INSERT INTO table SET memberID=?, programID=?, date_added=NOW()"); $stmt-&gt;execute(array($memberid, 155)); </code></pre> <p>I would normally create a simple loop for the array above which would call multiple instances of the sql statement and execute such as:</p> <pre><code>for($j = 0; $j &lt; (count($data)-1); $j++) { $stmt = $db-&gt;prepare("INSERT INTO table SET memberID=?, programID=?, date_added=NOW()"); $stmt-&gt;execute(array($memberid, $data[$j])); } </code></pre> <p>I do realize the code above is invalid ( $data[$j] ) but looking for the right way to do the call.</p> <p>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:</p> <pre><code>$sql = array(); foreach( $data as $row ) { $sql[] = '("'.$memberid.'", "'.$row[$j].'", NOW()")'; } mysql_real_query('INSERT INTO table (memberid, programid) VALUES '.implode(',', $sql)); </code></pre> <p>but with PDO I am not quite sure how this works, especially with placeholders (?). </p> <p>Any suggestions?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload