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条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序