我对数据库和复选框有疑问。我有一张桌子看起来像:
网站看起来像:
在页面底部我也有一个按钮,所以当我提交复选框时,数据库中的复选框将更新为1或0。 (是或否)
因此,当我点击训练下的第3个复选框时,它将使用用户/房间ID为“3583”更新数据库中的训练列。 (ID显示在屏幕右侧)
代码:
<form class='verwerkInfo' method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>?license=6'>
<td>
<?php if($room->trained == 1) { ?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked> <?php echo "Y"; } else{ ?> <input type='checkbox' name="<?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"; } ?>
</td>
<Td><?php echo $room->configuration; ?></td>
<td><?php echo $room->room_id; ?></td>
<td><?php var_dump($room->user_id); }?></td>
</tr>
所以我想我的复选框名称有问题。
查询看起来像:
$trainedQuery = "UPDATE room_users
SET trained = 1
WHERE user_id = $room->user_id";
$room->user_id
指的是数据库中的user_id。
答案 0 :(得分:2)
这是一种为复选框提供唯一名称并为每个元素传递额外信息的方法:
name="trained[<?php echo $room->room_id; ?>]" value="<?php echo $room->user_id; ?>"
然后在处理表单提交的PHP脚本中,您可以:
foreach ( $_POST['trained'] as $room_id => $user_id ) {
// This query needs protection from SQL Injection!
$trainedQuery = "UPDATE room_users SET trained = 1 WHERE user_id = $user_id";
}
目前尚不清楚 room_id 与 user_id 之间的关系是什么,以及仅使用 user_id更新 room_user 表的原因。您如何处理 room_id ?
这是你真正需要的:
// This query needs protection from SQL Injection!
$trainedClear = "UPDATE room_users SET trained = 0 WHERE user_id = $user_id";
$db->exec($trainedClear); // first clear all
foreach ( $_POST['trained'] as $room_id => $user_id ) {
// This query needs protection from SQL Injection!
$trainedQuery = "UPDATE room_users SET trained = 1
WHERE user_id = $user_id AND room_id = $room_id";
$db->exec($trainedQuery); // then add selections
}
// assuming there's a database connection `$db-exec`.
// Replace with your actual connection and query method.
为清晰起见,重构了复选框列:
<?php
$room_id = $room->id;
$room_configuration = $room->configuration;
$room_user_id = $room->user_id;
if ( $room->trained == 1 ) {
$trained_checked = 'checked';
$trained_label = 'Y';
}
else {
$trained_checked = '';
$trained_label = 'N';
}
if ( $room->active == 1 ) {
$active_checked = 'checked';
$active_label = 'Active';
}
else {
$active_checked = '';
$active_label = 'Inactive';
}
echo <<<EOT
<td><input type="checkbox" name="trained[$room_id]" value="$room_user_id" $trained_checked> $trained_label</td>
<td><input type="checkbox" name="active[$room_id]" value="$room_user_id" $active_checked> $active_label</td>
<td>$room_configuration</td>
<td>$room_id</td>
<td>$room_user_id</td>
EOT;
?>
答案 1 :(得分:1)
只需更改复选框名称属性,添加yes,no和active即可
name="yes_<?php echo $room->room_id; ?>" name="no_<?php echo $room->room_id; ?>" name="act_<?php echo $room->room_id; ?>"