dts777777 2017-03-20 14:34
浏览 32

too long

I am having trouble with form validation for checkboxes.

Here is the checkbox code:

<div class="form-group">
    <div class="checkbox checkbox-danger checkbox-inline">
        <input type="checkbox" name="defect[]" value="{$ng_id}">
    </div>
</div>

If I just do something like this then it echo's out whatever I select.

foreach($_POST['defect'] as $defects) {
echo $defects;
}

I have tried to use the empty function on its own as well as this:

if(empty($defects) || count($defects) < 1) {

but I just keep getting the error:

Undefined index: defect

</div>
  • 写回答

2条回答 默认 最新

  • doulun9534 2017-03-20 14:46
    关注

    A posted array is usually not set if nothing was ticked.

    You can do the following check if you want to also check it's an array:-

    if(@!is_array($_POST['defect'])){
        // Error
    } else {
        foreach($_POST['defect']){
            // do stuff
        }
    }
    

    This is suppressing the warning using @ otherwise you would get the "not defined" error.

    If you want to avoid that you could just do:

    if(!isset($_POST['defect'])){
       // Now check it's an array and has a count > 0
    }
    

    .. but in addition you still need to ensure it's an array and has a count greater than zero. The advantage with suppressing the warning in this specific instance is that you know it's an array PLUS you know there must be a value in it otherwise no array would have been passed in from the POST. It's one of those rare moments where suppressing the warning saves you doing 2 additional IF checks to avoid other warnings.You HAVE to check it's an array otherwise you will get the "invalid foreach" warning...

    评论

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因