【问题标题】:Submit multiple checkboxes to PHP向 PHP 提交多个复选框
【发布时间】:2013-06-06 03:14:46
【问题描述】:

我正在尝试在 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 都只更新一项。

【问题讨论】:

  • 你可能需要一个循环。
  • @SamiDzHamida — 喜欢foreach($synco as $item) {?
  • @SamiDzHamida 他已经在循环中了.. 只是使用了错误的条件
  • 是的,我意识到了。大声笑。
  • 不明白,你想做什么,我在$mmhclass-&gt;db-&gt;query("UPDATE table1之前没见过这种查询` SET [1] = '[2]' WHERE user_id = '[ 3]';", 数组($updaterow, $item, $user_profile['id']));`

标签: php sql forms checkbox


【解决方案1】:

代替

if ($synco == birthday) {

试试这个

if ($item == birthday) {

对于每个 $synco,您都处于 foreach 循环中,它被假定为 $item,因此您只需要检查 $item

【讨论】:

  • 我在问这里之前已经尝试过了,它没有用。不过更有意义。
【解决方案2】:
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.. 如果您在以下名称下有预定义的常量:生日、电子邮件、通用、网站......然后忽略这个:

你应该用引号括起来

例如:

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();

【讨论】:

  • 感谢您的提示,我做到了,但它并没有解决问题。
  • @MacGyver 您使用什么数据库 API? MySQLPDO 还是 MySQli?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-25
  • 1970-01-01
相关资源
最近更新 更多