我有一个php功能,只有选中复选框才会更新电子邮件。但是,即使复选框值为false,它也始终执行if语句。
如果选中复选框,我将if ($_POST['emailCheckbox'])
设置为仅执行查询,但由于某种原因,即使值为false,它也会每次都执行。
当未选中复选框时,这是$ _POST数组的值。否则它会打印出来。
数组([emailContact] => example@email.com [passwordContact] =>密码[firstNameContact] => John [emailCheckbox] => false)
$error = "";
if (!$_POST['passwordContact']) {
$error = "<p>You need to provide your password to make changes.</p>";
}
if ($error != "") {
echo $error;
exit();
}
$query = "SELECT * FROM users WHERE id=".$_SESSION['id']." LIMIT 1";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
if (!password_verify($_POST['passwordContact'], $row['password'])) {
$error = "<p>Your password is incorrect. Please try again.</p>";
} else if ($_POST['emailContact'] == "") {
$error = "<p>Enter new email address.</p>";
} else if (filter_var($_POST['emailContact'], FILTER_VALIDATE_EMAIL) == false) {
$error = "<p>Please enter a valid email address.</p>";
} else {
if ($_POST['emailCheckbox']) {
$queryEmailCheck = "SELECT * FROM users WHERE email = '".mysqli_real_escape_string($link, $_POST['emailContact'])."' LIMIT 1";
$resultEmailCheck = mysqli_query($link, $queryEmailCheck);
if (mysqli_num_rows($resultEmailCheck) > 0) {
$error = "That email address has already been taken.";
}
}
}
if ($error != "") {
echo $error;
exit();
} else {
if ($_POST['emailCheckbox']) {
$queryUpdate = "UPDATE users SET email='".mysqli_real_escape_string($link, $_POST['emailContact'])."', firstName='".mysqli_real_escape_string($link, $_POST['firstNameContact'])."' LIMIT 1";
} else {
$queryUpdate = "UPDATE users SET firstName='".mysqli_real_escape_string($link, $_POST['firstNameContact'])."' WHERE id='".$_SESSION['id']."' LIMIT 1";
}
print_r($_POST); //For testing purposes.
//mysqli_query($link, $queryUpdate);
echo 1;
}
}
在我的AJAX调用中,我有这段代码:
$.ajax({
type: "POST",
url: "actions.php?action=editMyContactDetails",
data: "emailContact=" + $("#emailContact").val() + "&passwordContact=" + $("#passwordContact").val() + "&firstNameContact=" + $("#firstNameContact").val() + "&emailCheckbox=" + $("#editEmailCheckbox").is(":checked"),
success: function(result) {
if (result == "1") {
console.log(result);
} else {
$("#editContactAlert").html(result).show();
}
}
})
如何在复选框值为true时确保if ($_POST['emailCheckbox'])
执行?
答案 0 :(得分:0)
您正在检查参数是否已通过(它始终是),因此它不会测试value
是"true"
还是"false"
e.g。你需要检查传递的值
if($_POST['emailCheckbox'] == "true"){...}
答案 1 :(得分:0)
$_POST
变量是字符串,除了空字符串true
和字符串""
之外,所有字符串都计算为"0"
。所以比较一个字符串:
if ($_POST['emailCheckbox'] == 'true') {
或者将一些字符串验证为布尔值(参见Validate Filters)。这里,字符串"true"
的计算结果为布尔true
,字符串"false"
的计算结果为布尔false
:
if (filter_var($_POST['emailCheckbox'], FILTER_VALIDATE_BOOLEAN)) {
或者,如果未选中则无法传递任何内容,如果选中则传递某些内容(true,1等),然后检查是否已设置,因为未检查的复选框将不会传递到{{1} } array:
$_POST