【问题标题】:PHP: How to store and checkboxes values and update themPHP:如何存储和复选框值并更新它们
【发布时间】:2013-12-27 20:39:50
【问题描述】:

我在存储和更新复选框值时遇到问题。 当我选择/取消选择它们时,它都可以工作,但是当我选择最后一个时,值设置为第一个未选中的框,依此类推。

HTML 表单:

echo'<input type="hidden" name="numOfRows" value="'.mysql_num_rows($query).'">';

if ($row[10]==1)
 {
  echo'<input type="checkbox" id="activateExam" name="activateExam[]" value="1" checked="checked">';
 }
else if ($row[10]==0)
 {
  echo'<input type="checkbox"  id="activateExam"  name="activateExam[]" value="0" >';
 }
echo'<input type="hidden" name="id[]" value="'.$row[0].'">';

PHP 代码:

for ($i = 0; $i < $_POST['numOfRows']; $i++)
{
if (isset($_POST['activateExam'][$i]))
{
    $activateExam = '1';
}
else
if (!isset($_POST['activateExam'][$i]))
{
    $activateExam = '0';
}

$id = $_POST['id'][$i];
echo "exam" . $activateExam . " id: " . $id;
$sql = "UPDATE `student` SET `activateExam`='" . $activateExam . "' WHERE `ID`='" . $id . "'";
$query = mysql_query($sql);
if (!$query) echo "Database Error : " . $sql;
}

希望你能帮忙,谢谢。

【问题讨论】:

  • $_POST['numOfRows'] 在哪里?
  • 对不起,我忘了复制它,它现在在那里。
  • 尝试给出的答案。我想你想激活他们被选中和不活跃的其他人。

标签: php mysql arrays forms checkbox


【解决方案1】:

试试看

HTML

if ($row[10]==1)
 {
  echo'<input type="checkbox" id="activateExam" name="activateExam[]" value="'.$row[0].'" checked="checked">';
 }
else if ($row[10]==0)
 {
  echo'<input type="checkbox"  id="activateExam"  name="activateExam[]" value="'.$row[0].'" >';
 }

和php

mysql_query("UPDATE `student` SET `activateExam`=0 ") or die(mysql_error()); // update all to 0

if(isset($_POST['activateExam']))
{
   $arr_active_exam = $_POST['activateExam'];
   if(sizeof($arr_active_exam)>0)
   {
      foreach($arr_active_exam as $id)
      {
          mysql_query("UPDATE `student` SET `activateExam`=1  WHERE id='$id' ") or die(mysql_error()); // update all to 1 which is checked 
      }
   }
}

【讨论】:

  • 如果您的 id 列是主键,您可以使用限制 1。作为 WHERE id='$id' LIMIT 1
猜你喜欢
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多