Problems adding multiple records in PHP

I have a form and script which is supposed to insert multiple records (MOT dates and readings) for a car with a specific ID.

I use this code to output a number of rows in the form:

      $output = ""; 
    $desired_row_count = 20;  
     
    for ($i=0; $i<$desired_row_count; $i++) { 
     $output .= ' <div class="addnewcar-wide"><label for="_MotDate">Date</label><input name="_MotDate['.$i.']" type="text" 

size="10" /><label for="_MotOdometer">Odometer</label><input name="_MotOdometer['.$i.']" type="text" size="20" /></div>'; 
    } 
    echo $output; 

This works fine in that it outputs the rows.

Then in the form handler script:

$motdate = $mysqli->real_escape_string($_POST['_CarID']);   
$motdate = $mysqli->real_escape_string($_POST['_MotDate']);    
$motodometer = $mysqli->real_escape_string($_POST['_MotOdometer']);  
  

// loop through motDate array and add to INSERT statement    
for ($i=0; $i<count($motdate); $i++) {    
    if ($motdate[$i]!="" && $motodometer[$i]!="") {  
        $addmotdetails = $mysqli->query('INSERT INTO mothistorytable (`carid`,`motdate`,`motodometer`) VALUES ('.$carid.',"'.

$motdate[$i].'","'.$motodometer[$i].'")');    
    }  
} 

If I echo $addmotdetails it doesn’t show anything, so the data clearly isn’t coming through at all. I checked the database

table and the records aren’t being added. Guess I’m missing something but the process doesn’t show any errors so I’ve no idea

why it’s not working. Any ideas?

Thanks

$_POST[‘_MotDate’] is not a string. It’s an array. Same for the odometer.

Also:

Danger Will Robinson.

Thanks, so in that case what should I set the $motdate variable to?

Think I’ve sorted it actually- I just removed the escape string, so it’s just $motdate = $_POST[‘_MotDate’];

Thanks for the pointer

For further reading, start looking at using prepared statements and/or combining your inserts into a single query.

When escaping is removed the query becomes vulnerable to SQL injection attacks. You should be using prepared statements with variable bindings if this is new code not programming as if it was a decade ago. Using mysqli escaping is just as vulnerable to attacks as mysql_* procedural family of functions fyi.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.