这是我创建的一个更新页面的一部分,我可以使某些图像私有,如果勾选。 这是我的表格:
/* MYSQL rows - Photo ID & Privacy */
$photo_id = $row['id'];
$photo_private = $row['private'];
/* Privacy setting for photo(s) */
if ($photo_private == "1") {
echo '<input type="checkbox" name="private_photo['.$photo_id.']" value="1" checked>';
} else {
echo '<input type="checkbox" name="private_photo['.$photo_id.']" value="0">';
}
下面是我的表单提交到的页面。 我可以很好地获得照片ID,但我不知道如何将value=“x”保存到$value中
foreach ($_POST['private_photo'] as $plz_pvt) {
$value = $_POST['private_photo'];
$sql = "UPDATE photos SET private='$value' WHERE id='$plz_pvt'";
$result = mysqli_query($con, $sql);
}
首先,去掉带有value=“0”
的复选框。 这并不是你所期望的工作方式。 如果一个复选框没有被选中,它就根本不会被发送到服务器。 这意味着如果它被选中,它将发送值0
,因此它永远不会被正确设置。
接下来,添加一个具有相同名称和value=“0”
的隐藏输入。 如果将此输入置于复选框之前,则如果该复选框未被选中,则将其发送到服务器。 如果选中复选框,它将覆盖此隐藏输入。
//ternary - variable holds 'checked' if `$photo_private == 1`, or an empty string if not.
$is_checked = $photo_private == "1" ? 'checked' : '';
//hidden input - Submitted if checkbox is not checked.
echo '<input type="hidden" name="private_photo['.$photo_id.']" value="0">';
//checkbox - overwrites previous hidden input if checked.
//Utilizes `$is_checked` to check the checkbox by default when appropriate
echo '<input type="checkbox" name="private_photo['.$photo_id.']" value="1" '.$is_checked.'>';
这应该能工作,因为如果选中复选框,它将覆盖隐藏输入中的值。 如果未选中,将提交隐藏的输入值。