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 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计