我有一个游戏,用户信息将在每次完成游戏后的调查时插入到数据库中,所以我在网站上以表格格式显示这些信息,下面有一个提交按钮,所以当点击它时将检查已检查和未选中的框并更新数据库中布尔值的值,但目前我能够检查已选中的复选框,但在提交时未检查的那些未在数据库中更新。
这是我的代码,用于检查取消选中和提交时的复选框
<?php
include_once("dcConnect.php");
if(!empty( $_POST['myCheckBox'] )){
$strAllUsernameCombined = implode("','", $_POST['myCheckBox']);
$sql = "UPDATE dcUsers SET dcChecked = 1 WHERE dcID IN ('{$strAllUsernameCombined}')";
mysqli_query($link, $sql) or exit("result_message=Error");
} else {
$strAllUsernameCombined = implode("','", $_POST['myCheckBox']);
$sql = "UPDATE dcUsers SET dcChecked = 0 WHERE dcID IN ('{$strAllUsernameCombined}')";
mysqli_query($link, $sql) or exit("result_message=Error");
}
?>
以下是我如何显示数据库中的数据
<p>
<form action="default3.php" method="post"</form>
<?php
include_once("dcConnect.php");
$dcData = "SELECT dcChecked, dcID, dcServerName, dcServerOc, dcServerAge, dcServerGender, dcServerMarital, dcServerCode, dcServerPoints FROM dcUsers";
$result = $link->query($dcData);
if($result->num_rows >0){
echo"<table><tr><th>Redeem</th><th>ID</th><th>Name</th><th>Occupation</th><th>Age Group</th><th>Gender</th><th>Marital Status</th><th>Code</th><th>Points</th></tr>";
while($row = $result->fetch_assoc()){
echo "<tr><td></input><input type='checkbox' id='". $row["dcID"] ."' name='myCheckBox[]' value='". $row["dcID"] ."'".(($row["dcChecked"]) ? 'checked="checked"':"")." ></input></td><td>". $row["dcID"] ."</td><td>". $row["dcServerName"] ."</td><td>". $row["dcServerOc"] ."</td><td>". $row["dcServerAge"] ."</td><td>". $row["dcServerGender"] ."</td><td>". $row["dcServerMarital"] ."</td><td>". $row["dcServerCode"] ."</td><td>". $row["dcServerPoints"] ."</td></tr>";
}
echo "</table>" ;
}else{
echo"no results";
}
$link->close();
?></p>
<input type="submit" name="submitter" value="Save">
</form>
答案 0 :(得分:2)
提交后的HTML复选框将丢失值。你需要添加一个隐藏的输入 BEFORE 那个复选框
<input type='hidden' name='myCheckBox[0]' value='0'>
<input type='checkbox' id='". $row["dcID"] ."' name='myCheckBox[]' value='". $row["dcID"] ."'".(($row["dcChecked"]) ? 'checked="checked"':"")." >
但是我想你希望每个未选中框都默认为0:阅读完网站后,首选下一种方法:
<input type='hidden' name='myCheckbox[". $row['dcID'] ."]' value='0'>
<input type='checkbox' name='myCheckBox[". $row['dcID'] ."]'
value='1'". ($row['dcChecked'] ? ' checked' : '') .">
这是用于更新MySQL位的PHP:
if (isset($_POST['myCheckBox'])) {
$yes = $no = array();
foreach ($_POST['myCheckBox'] as $dcID => $dcChecked) {
if ($dcChecked) {
$yes[] = $dcID;
} else {
$no[] = $dcID;
}
}
if (count($yes)) {
$sql = 'UPDATE dcUsers SET dcChecked = 1 WHERE dcID IN ('. implode(',', $yes) .')';
mysqli_query($link, $sql) or exit("result_message=Error");
}
if (count($no)) {
$sql = 'UPDATE dcUsers SET dcChecked = 0 WHERE dcID IN ('. implode(',', $no) .')';
echo $sql; //delete this line after debugging
mysqli_query($link, $sql) or exit("result_message=Error");
}
}