我是PHP的新手,我正在寻找一种方法将多个复选框的值提交到数据库中!现在我设法让Checkbox显示为Checked,如果数据库中的值= 1,否则将取消选中。
以下是我当前的代码。
<?php
$query = "SELECT * FROM users_achievements_xbox WHERE user_id = '$userID' && game_id = '$gameID' ORDER BY achievement_id ASC";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) { // Start looping table row
$userID = $row['user_id'];
$gameID = $row['game_id'];
$achievementID = $row['achievement_id'];
$achievementName = $row['achievement_name'];
$achievementDescription = $row['achievement_description'];
$achievementValue = $row['achievement_value'];
$check = mysql_query("SELECT * FROM users_achievements_xbox WHERE user_id = '$userID' && game_id = '$gameID' && achievement_id = '$achievementID'");
$row2 = mysql_fetch_assoc($check);
$achievement_locked = $row2['achievement_locked'];
if($achievement_locked == "0")
{
$checked = 'checked="checked"';
}
else
{
$checked = "";
}
?>
<tr align="center" bgcolor="#eeeeee">
<td> <img src="images/achievements/<?php echo $gameID; ?>/<?php echo $achievementID; ?>.jpg" /> </td>
<td> <?php echo $achievementName; ?> </td>
<td> <?php echo $achievementDescription; ?> </td>
<td> <?php echo $achievementValue; ?> </td>
<td> <input type="checkbox" name="checkbox" value="0" <?php echo $checked ?> /> </td>
</tr>
<?php
} // end of while loop
?>
我正在考虑通过isset尝试这样做,但我不想要一个循环的提交按钮我似乎无法找到如何在表单中包装Checkbox但是当我快速测试它时,每个值在我的数据库中的“achievement_locked”变为0时,我只希望选中的复选框如果选中则更改为0,否则更改为1!
感谢您的帮助!
答案 0 :(得分:0)
这是一个例子。理解。我还没有转义POST变量。确保你这样做。
HTML文件:
<form name="form1" method="post" action="test.php">
<p>
<input name="colors[]" type="checkbox" id="colors[]" value="0">
Red
<input name="colors[]" type="checkbox" id="colors[]" value="0">
Blue
<input name="colors[]" type="checkbox" id="colors[]" value="0">
Green</p>
<p>
<input name="colors[]" type="checkbox" id="colors[]" value="0">
Yellow
<input name="colors[]" type="checkbox" id="colors[]" value="0">
Brown </p>
<input type="submit">
</form>
这是你的php文件应该有的。
<?php
$colors = $_POST['colors'];
$red = isset($colors[0]) ? 1 : 0;
$blue = isset($colors[1]) ? 1 : 0;
$green = isset($colors[2]) ? 1 : 0;
$yellow = isset($colors[3]) ? 1 : 0;
$brown =isset($colors[4]) ? 1 : 0;
// query
$sql = "INSERT INTO table (red,blue,green,yellow,brown) VALUES (:red,:blue,:green,:yellow,:brown)";
$q = $conn->prepare($sql);
$q->execute(array(':red'=>$red,
':blue'=>$blue,
':green'=>$green,
':yellow'=>$yellow,
':brown'=>$brown));
?>