dongyan3616 2017-09-26 17:18
浏览 188
已采纳

从表单中获取数组

I have a form that uses a checkbox and it gets all the data from the mysql database. So there could be from 1 to unlimited of the checkboxes.

I need to get each of those that are checked when the form is submitted.

It works if all of them are checked, but if only a few are checked, it will either show none or just one of them.

Here is the code I am using to show the checkboxes with data:

while ($myrow = mysqli_fetch_array($result)){
echo<<<END
<input type="checkbox" id="units" name="unit[$i]" value="$myrow[unit_id]" /> $myrow[unit_id]<br />
END;
$i++;
}//end while

Here is the code I am using when the form is submitted:

$i=0;
while($_POST["unit"][$i] != ""){
$unit = $_POST["unit"][$i];
$unit = $res2->real_escape_string($unit);
echo $unit."<br />";
$i++;
} // end while

I believe the problem is the fact that I have while($_POST["unit"[$1] != "") and if one box is checked and then another one 2 or 3 down is checked, it sees the 2nd one empty and stops.

If that's the case, I need help to figure out how to make it run through them all and print out the ones that were checked. Remember, there could be anywhere from 1 to unlimited checked so it can't be a set number like while($i <= 50)

Thank you!

  • 写回答

2条回答 默认 最新

  • doudou5421 2017-09-26 17:22
    关注

    Checkboxes are only sent when they are checked. With while the loop stops as soon as a checkbox denoted by $_POST['unit'][$i] is not set, so the rest never get evaluated. You should consider using foreach for arrays:

    foreach($_POST["unit"] as $unit) {
        echo $unit . "<br />";
    }
    

    If the key is important:

    foreach($_POST["unit"] as $key => $unit) {
        echo $key . " is " . $unit . "<br />";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码