问题
I've got a question.
I've got a page with hundreds of checkboxes wich are generated with the Database. So when the database returns 1 it is checked otherwise it is 0 and not checked. When I try to check the checkbox and try to update that into the database, some checkboxes are randomly checking out..
Code:
This is the Query
if(isset($_POST['submit'])){
foreach ($_POST['untrain[{$room->room_id}]'] as $room_id) {
// This query needs protection from SQL Injection!
$user_id;
$room_id;
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE room_id = $room_id";
$db->update($untrainQuery);
}
}
These are the checkboxes:
<?php
if ($room->trained == 1) {
?> <input type='checkbox' value="<?php
echo $room->user_id;
?>" name="trained[<?php
echo $room->room_id;
?>]" checked> <?php
echo "Y";
} else if ($room->trained == 0) {
?> <input type='checkbox' value="<?php
echo $room->user_id;
?>" name="untrain[<?php
echo $room->room_id;
?>]"> <?php
echo "N";
}
?> </td>
<Td><?php
if ($room->active == 1) {
?> <input type='checkbox' name="<?php
echo $room->room_id;
?>" checked> <?php
echo "Active";
} else {
?> <input type='checkbox' name="<?php
echo $room->room_id;
?>" <?php
echo "Inactive";
}
?>
So when the database returns 1 the checkbox is checked otherwise it is 0 so unchecked.. So my question is why it is randomly checking out checkboxes?
I want to check the checkboxes to update the database with 1, but sometimes it randomly checking out checkboxes?!
回答1:
Your logic has the following flaws: your $_POST
array has the key untrain
and its value is an internal array of keys room_id
(because they are in the checkbox name) and values user_id
(checkbox's values). In your foreach loop $room_id
has assingned the values of checkboxes, which are indeed user_ids
. Besides you should iterate over $_POST['untrain']
, I don't know where you take that key $room->room_id
from.
I would change that to:
if(isset($_POST['submit'])){
foreach ($_POST['untrain'] as $room_id => $user_id) {
//sanitize $room_id
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE room_id = $room_id";
$db->update($untrainQuery);
}
}
Or, if you have an array of all room_ids, you can iterate over them to check if which are checked:
if(isset($_POST['submit'])){
foreach ($room_ids as $room_id) {
//sanitize $room_id
if(isset($_POST["untrain[{$room_id}]"]){//that is, if it was checked
$trained = 1;
}else{
$trained = 0;
}
$untrainQuery = "UPDATE room_users SET trained = $trained WHERE room_id = $room_id";
$db->update($untrainQuery);
}
}
来源:https://stackoverflow.com/questions/29486911/checkboxes-are-checking-out-randomly