我想弄清楚为什么下面的查询不起作用。基本上,它会检查是否选中了复选框,是否是与变量相关的复选框,因此mysql记录设置为1。如果未选中复选框,则将其设置为0。我添加了多个不同的疑难解答和错误报告片段-没有错误。但没有成功?这把我逼疯了。欢迎任何建议!非常感谢。
if(isset($_POST['updateUser'])){
$mysqli = mysqli_connect($config['host'],
$config['user'],
$config['pass'],
$config['db']);
foreach($_POST as $k => $v) {
$check[$k] = isset($_POST[$k]) ? 1 : 0;
}
$query = "UPDATE users_permissions SET editComments = ?,
editTopics = ?,
editArticles = ?,
autoApprove = ?,
allowArticleMod = ?,
courseAuthor = ?,
seeFinance = ?,
editUsers = ?,
editUsersPermissions = ?,
editSuperUsers = ?,
editWL = ?
WHERE
userid = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('iiiiiiiiiiii',
$check['editComments'],
$check['editTopics'],
$check['editArticles'],
$check['autoApprove'],
$check['allowArticleMod'],
$check['courseAuthor'],
$check['seeFinance'],
$check['editUsers'],
$check['editUsersPermissions'],
$check['editSuperUsers'],
$check['editWL'],
$profileData['userid']);
$profileData['userid']);
$stmt->execute();
}
更新:对代码所做的更改以反映@Floris 的建议
$checks = [];
foreach($_POST as $k => $v) {
$checks[$k] = isset($_POST[$k]) ? 1 : 0;
}
现在,您有一个名为$checks
的数组,它具有以前的所有$_POST
键,根据是否设置了值0/1,您可以跳过一大堆丑陋的代码!耶!现在,只需将bind_param
变量替换为$check变量即可。
编辑-更多代码,带评论:
//Go through each variable in the $_POST array, using "$k" to refer to the key and "$v" to the value,
//So, $_POST["editComments"] = "foo" would have $k = "editComments" and $v = "foo"
foreach($_POST as $k => $v) {
//This is a shorthand if-statement which basically means: if isset($_POST[$k]) == true, $checks[$k] = 1. Else, $checks[$k] = 0.
$checks[$k] = isset($_POST[$k]) ? 1 : 0;
}
//Nothing new here
$query = "UPDATE users_permissions SET editComments = ?,
editTopics = ?,
editArticles = ?,
autoApprove = ?,
allowArticleMod = ?,
courseAuthor = ?,
seeFinance = ?,
editUsers = ?,
editUsersPermissions = ?,
editSuperUsers = ?,
editWL = ?
WHERE
userid = ?";
$stmt = $mysqli->prepare($query);
//So here's how to bind the $checks variables:
$stmt->bind_param('iiiiiiiiiiii', $checks["editComments"],
$checks["editTopics"], //and so on
$editArticles,
$autoApprove,
$allowArticleMod,
$courseAuthor,
$seeFinance,
$editUsers,
$editUsersPermissions,
$editSuperUsers,
$editWL,
$profileData['userid']);
$stmt->execute();