duanchuanqu593743 2012-07-26 15:46
浏览 203
已采纳

保存选中的值复选框数组POST

I have a list of checkboxes and save the checked values in an array. However, when someone clicks 'submit' and they get an error, all their checked boxes are forgotten. Usually I would let the script remember the checked boxes with a code like

IF checkbox value = OK { echo checked="checked"}

However, now I save it in an array and I have no idea how to do this?

<?php

$sql = "SELECT merknaam FROM merken";
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result)) {
    echo "&nbsp;&nbsp;<input type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'>&nbsp;" . $row['merknaam'] . " <Br />  ";
}

?>

This is the code I use for the checkboxes. Next I display the array with this code:

$merkenstring = implode(",", $_POST['merken']);

echo $merkenstring;

Result: AC Ryan,Adidas,Agu,Cargo

I hope someone could give me a code example!

  • 写回答

2条回答 默认 最新

  • douyou9923 2012-07-26 15:50
    关注

    Assuming you are posting this to the same page, and $_POST['merken'] is still available after an error, use in_array() to test each checkbox's value against the current set in $_POST:

    while ($row = mysql_fetch_array($result)) {
        // If the current value is in the $_POST['merken'] array
        // and the array has been initialized...
        if (isset($_POST['merken']) && is_array($_POST['merken']) && in_array($row['merknaam'], $_POST['merken'])) {
          // Set the $checked string
          $checked = "checked='checked'";
        }
        // Otherwise $checked is an empty string
        else $checked = "";
        // And incorporate it into your <input> tag
        echo "&nbsp;&nbsp;<input $checked type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'>&nbsp;" . $row['merknaam'] . " <Br />  ";
        //----------------------^^^^^^^^^^
    }
    

    If this was posted to a different script, you would (as with any post value returned to a previous script) need to store the array in $_SESSION instead and compare against $_SESSION['merken'] in your in_array() call.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考