doujiao2000 2015-06-23 12:55
浏览 43
已采纳

foreach重复复选框字段

I get values to "$val" 1 and 4. The products_extra_fields_id 1 and 4 have checkbox field checked plus another checkbox in other products_extra_fields_id's I have two checkboxes. How can I avoid duplicate checkbox fields.

<?php                       
$extra_fields_query = mysql_query("SELECT * FROM products_extra_fields");
while ($extra_fields = mysql_fetch_array($extra_fields_query)){

    foreach ($HTTP_POST_VARS['extra_field'] as $key=>$val){
//$val get values 1 and 4

        echo "<input type='checkbox' name='extra_field[".$extra_fields['products_extra_fields_id']."]' value='".$extra_fields['products_extra_fields_id']."' " . (($extra_fields['products_extra_fields_id'] == $val) ? checked : false). " >";
    }
    } ?>

enter image description here

  • 写回答

1条回答 默认 最新

  • dqnqpqv3841 2015-06-23 19:20
    关注

    You are seeing duplicate checkboxes because, for every row you pull from the database, you are looping over the extra_field data posted by the user. There are two values in $HTTP_POST_VARS['extra_field'] so you get two checkboxes per row.

    Instead of ($extra_fields['products_extra_fields_id'] == $val) you should use in_array to test whether the checkbox is checked in each case.

    $HTTP_POST_VARS is very old and was deprecated in PHP 4.1 in 2001. Instead you should use $_POST which is a superglobal. This means you do not have to use global before using it in a function.

    checked is a string and should be enclosed in quotes in your echo statement.

    The following should fix all these issues:

    $extra_fields_query = mysql_query("SELECT * FROM products_extra_fields");
    while ($extra_fields = mysql_fetch_array($extra_fields_query)) {
        echo "<input type='checkbox' name='extra_field["
          . $extra_fields['products_extra_fields_id'] . "]' value='"
          . $extra_fields['products_extra_fields_id'] . "' "
          . (in_array($extra_fields['products_extra_fields_id'], $_POST['extra_field'])
               ? "checked" : "")
          . " >";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动