Wednesday, 21 August 2013

How can $_POST pass input variables to MySQL query as integers, not 1?

How can $_POST pass input variables to MySQL query as integers, not 1?

I have a table of numbers where the user should be able to edit the values
and have the database updated on submit.
So far, my faulty code is updating every field with the value 1 on submit,
regardless of what has been inputted.
Code on submit:
//If the confirm button has been hit:
if (isset($_POST['submit'])) {
//Create the foreach loop
foreach($_POST['classtoupdate'] as $classes){
//Grab the POST data and turn it into integers
$class_id = (int)$classes;
$totalspcs = (int)$_POST['allspaces'];
$totalbkgs = (int)$_POST['allbookings'];
$newbies = (int)$_POST['noobs'];
//Change the booking numbers:
$newdeets = "UPDATE classes SET total_spaces = '$totalspcs',
total_bookings = '$totalbkgs', free_spaces = ('$totalspcs' -
'$totalbkgs'), newbies = '$newbies' WHERE class_id = '$class_id')";
echo $newdeets;
mysqli_query($dbc, $newdeets);
}
mysqli_close($dbc);
echo 'All good, yay! <a href="admin.php">Go look</a>';
}
Form:
//create the form
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '" >';
echo '<tr><td>' . $class . '</td>';
echo'<td>' . $new_date . '</td>';
echo '<td>' . $new_time . '</td>';
echo '<td><input type="text" maxlength="2" class="input-mini"
name="noobs[]" id="noobs[]" value="' . $newbies . '">';
echo '<td><input type="text" maxlength="2" class="input-mini"
name="allspaces[]" id="allspaces[]" value="' . $totalspaces . '">';
echo '<td><input type="text" maxlength="2" class="input-mini"
name="allbookings[]" id="allbookings[]" value="' . $bookings . '"
>';
echo '<td>' . $freespaces . '</td>';
echo' <input type="hidden" name="classtoupdate[]"
id="classtoupdate[]" value="' . $class . '" />';
}
echo'</table>';
// Make booking button
echo '<input type="submit" name="submit" class="btn btn-large
btn-primary pull-right" value="Update">';
echo '</form>';
The echoed query results after inputting random values (not 1) in the form:
UPDATE classes SET total_spaces = '1', total_bookings = '1', free_spaces =
('1' - '1'), newbies = '1' WHERE class_id = '26')
UPDATE classes SET total_spaces = '1', total_bookings = '1', free_spaces =
('1' - '1'), newbies = '1' WHERE class_id = '16')
..and so on for each table row. I can't find the problem replicated after
extensive searching on SO and in the manuals.
I've tried intval(), serialize and array_map on the POST results (probably
incorrectly); I've tried different foreach loops to translate them into
integers, still no joy.
Any advice?

No comments:

Post a Comment