Asked  7 Months ago    Answers:  5   Viewed   28 times

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?



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);
Wednesday, March 31, 2021
answered 7 Months ago

Ok after a few trial and errors and some help from @Rizier123, here is the answer:

html on the form page

For clarity sake, I was trying to figure out how add several arrays of data to my db. So on dynamic form page, I have inputs similar to:

<p>Location: <input type='text' name='location[]'  > </p>

Processing the Form and Inputting the Data to the DB

First, I switched from mysqli to PDO, then I ran with the following code:

try {
        $sql = "INSERT INTO location_info (`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries`, `non_rec_injuries_timeframe`, `competitor`, `cost_per_pair`, `usage_rate`, `leakage`, `cost_of_productivity`, `non_rec_impact`, `non_rec_sprain`, `non_rec_puncture`, `non_rec_dermatitis`, `non_rec_infection`, `non_rec_burns`, `non_rec_cuts`, `rec_impact`, `rec_sprain`, `rec_puncture`, `rec_dermatitis`, `rec_infection`, `rec_burns`, `rec_cuts`, `condition`, `general_id`)
        VALUES (:department, :participant, :activity, :location, :rec_injuries, :rec_injuries_timeframe, :non_rec_injuries, :non_rec_injuries_timeframe, :competitor, :cost_per_pair, :usage_rate, :leakage, :cost_of_productivity,:non_rec_impact, :non_rec_sprain, :non_rec_puncture, :non_rec_dermatitis, :non_rec_infection, :non_rec_burns, :non_rec_cuts, :rec_impact, :rec_sprain, :rec_puncture, :rec_dermatitis, :rec_infection, :rec_burns, :rec_cuts, :condition, '{$id}')";

        $stmt = $db->prepare($sql);

for($i = 0, $l = count($_POST["department_name"]); $i < $l; $i++) { 

    $loc_info = array(':department' => $_POST["department_name"][$i],
                        ':participant' => $_POST["participant_name"][$i],
                        ':activity' => $_POST["activity"][$i],
                        ':location' => $_POST["location"][$i],
                        ':rec_injuries' => $_POST["injuries"][$i],
                        ':rec_injuries_timeframe' => $_POST["injury_time_frame"][$i],
                        ':non_rec_injuries' => $_POST["non_rec_injuries"][$i],
                        ':non_rec_injuries_timeframe' => $_POST["non_rec_injury_timeframe"][$i],
                        ':competitor' => $_POST["competitor"][$i],
                        ':cost_per_pair' => $_POST["cost_per_pair"][$i],
                        ':usage_rate' => $_POST["usage_rate"][$i],
                        ':leakage' => $_POST["leakage"][$i],
                        ':cost_of_productivity' => $_POST["cost_of_productivity"][$i],
                        ':non_rec_impact' => $_POST["non_rec_impact"][$i],
                        ':non_rec_sprain' => $_POST["non_rec_sprain"][$i],
                        ':non_rec_puncture' => $_POST["non_rec_puncture"][$i],
                        ':non_rec_dermatitis' => $_POST["non_rec_dermatitis"][$i],
                        ':non_rec_infection' => $_POST["non_rec_infection"][$i],
                        ':non_rec_burns' => $_POST["non_rec_burns"][$i],
                        ':non_rec_cuts' => $_POST["non_rec_cuts"][$i],
                        ':rec_impact' => $_POST["impact"][$i],
                        ':rec_sprain' => $_POST["sprain"][$i],
                        ':rec_puncture' => $_POST["puncture"][$i],
                        ':rec_dermatitis' => $_POST["dermatitis"][$i],
                        ':rec_infection' => $_POST["infection"][$i],
                        ':rec_burns' => $_POST["burns"][$i],
                        ':rec_cuts' => $_POST["cuts"][$i],
                        ':condition' => $_POST["condition"][$i] );

Wednesday, March 31, 2021
answered 7 Months ago


$_SESSION['question'] = $que; 

print_r($_SESSION['question'][0]); will give you first question.

Saturday, May 29, 2021
answered 5 Months ago

This got it done. Thanks to Marc B for his thoughts:

$e = 0;

$units = 0;
$r = 0;

    foreach ($Boxes[$e] as $a => $b)  

        $zzz[] = $Boxes[$e][$r];

$ce = count($Boxes[$e]);        

//end inner foreach

$products = implode(',', array_fill(0,$ce, '?'));

$db = new PDO('mysql:host= ;dbname=Tracking', $dbuser,$dbpass);
$stmt = $db->prepare("SELECT Box_Num,Timestamp,E3_SN,Assy_Status FROM Current_Box WHERE Box_Num IN( $products )");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Saturday, May 29, 2021
answered 5 Months ago

SQL Injection is only a problem where user-entered data needs to be sent to your database. A query like SELECT * FROM Player includes no user data. It's entirely safe from SQL Injection for that reason.

In fact, in this case, there's no benefit in using a prepared statement. A prepared statement here will make two calls to the database when one will do.

You can do this:

$getPlayers = $db->query("SELECT * FROM Player");
foreach ($getPlayers as $player) {
  // do something

No preparation, no binding, and just one call to the database.

Saturday, May 29, 2021
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :