我正在尝试在POST方法中向PHP提交多个复选框。每个选中的项应返回一个简单的SQL查询,这是我目前的代码:
HTML:
<input type="checkbox" name="synco[]" value="email" checked="checked" /> Sync email
<input type="checkbox" name="synco[]" value="birthday" checked="checked" /> Sync birthday
<input type="checkbox" name="synco[]" value="gender" checked="checked" /> Sync gender
<input type="checkbox" name="synco[]" value="bio" checked="checked" /> Sync bio
<input type="checkbox" name="synco[]" value="website" checked="checked" /> Sync website
PHP:
$synco = $_POST['synco'];
if(empty($synco))
{
// Empty selection Error
}
else
{
foreach($synco as $item) {
if ($synco == birthday) {
$item = $birthday;
$updaterow = birthday;
}
elseif ($synco == email) {
$item = $user_profile[email];
$updaterow = email_address;
}
elseif ($synco == gender) {
$item = $gender;
$updaterow = gender;
}
elseif ($synco == website) {
$item = $user_profile[website];
$updaterow = website;
}
else {
$item = $user_profile[bio];
$updaterow = bio;
}
$mmhclass->db->query("UPDATE `table1` SET `[1]` = '[2]' WHERE `user_id` = '[3]';", array($updaterow, $item, $user_profile['id']));
// JSON Message
}
问题是:当我提交表单时,无论检查了多少输入,sql都只更新1个项目。
答案 0 :(得分:1)
而不是
if ($synco == birthday) {
试试这个
if ($item == birthday) {
你在每个$ synco的foreach循环中它被假定为$ item,所以你只需要检查$ item
答案 1 :(得分:1)
foreach($synco as $item) {
if ($synco == birthday) {
$item = $birthday;
$updaterow = birthday;
}
elseif ($synco == email) {
$item = $user_profile[email];
$updaterow = email_address;
}
elseif ($synco == gender) {
$item = $gender;
$updaterow = gender;
}
elseif ($synco == website) {
$item = $user_profile[website];
$updaterow = website;
}
你应该使用$item
代替$synco
更多..如果你有以下名称的预定义常量:生日,电子邮件,gener,网站......然后忽视这个:
你应该在引号中包装
例如:
if ($item == "birthday"){
}
尝试为查询使用替代样式:
原件:
$mmhclass->db->query("UPDATE `table1` SET `[1]` = '[2]' WHERE `user_id` = '[3]';", array($updaterow, $item, $user_profile['id']));
我接近的方式:
$mmhclass->db->query("UPDATE `table1` SET `".$updaterow."`= '".$item."' WHERE `user_id`= '".$user_profile['id']."'");
或者使用准备好的声明:
$Query = $mmhclass->db->prepare("UPDATE `table1` SET ?=? WHERE user_id=?");
$Query->bind_param('ssi',$updaterow,$item,$user_profile['id']);
$Query->execute();
$Query->close();