在编辑表单上填充复选框 [英] Populate Checkboxes on Edit Form

查看:49
本文介绍了在编辑表单上填充复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个编辑页面,该页面在访问时被填充.输入值工作正常,但是我很难勾选类别复选框.我从两个表中获取信息.一个显示所有类别,另一个显示与该项目关联的类别.

I have an edit page that gets populated when accessed. The input values work fine, but I'm having a hard time ticking the category checkboxes. I get the information from two tables. One that displays all the categories and the other one that gets the categories associated with the item.

以下代码不起作用,因为第二个while语句在第一轮中完成了循环.有适当的方法可以做到这一点吗?

The following code doesn't work because the second while statement finishes its loop in the first round. Is there an appropriate way to do this?

<?php $check_cats = mysql_query("SELECT * FROM item_categories WHERE itemid = '$itemid'") or die(mysql_error()); ?>
<?php $result = mysql_query("SELECT * FROM categories ORDER BY cname") or die(mysql_error()); ?>

<?php while($row = mysql_fetch_array( $result )) { ?>
    <input type="checkbox" id="<?php echo $row['cname']; ?>" name="cat[]" value="<?php echo $row['id']; ?>" 
<?php while($check_cat_rows = mysql_fetch_array( $check_cats )) {
    if ($check_cat_rows['catid'] == $row['id']) {
      echo 'checked="yes"';
    }
  }
} ?>

我的两个桌子:

TABLE `item_categories`
  `id`
  `itemid`
  `catid`

TABLE `categories`
  `id`
  `cname`

推荐答案

您的整体结构不正确,您不能假设两个结果会完美地对齐,并且循环是错误的.试试这个:

Your whole thing is structured incorrectly, you can't assume the two results will line up perfectly, and your loops are wrong. Try this:

SELECT *,
(case when id IN
(SELECT catid FROM item_categories WHERE itemid = '$itemid')
then 1 else 0 end) checked
FROM categories ORDER BY cname

现在,您只需运行一个查询,并有一个漂亮的 $ row ['checked'] 即可使用!

Now you just run the one query and have a nice little $row['checked'] to use!

SELECT *, 
(case when categories.id IS NOT NULL
then 1 else 0 end) checked
FROM item_categories
LEFT JOIN categories
ON (item_categories.catid = categories.id)
WHERE itemid = '$itemid'

基于marc B和我的混合文件进行了改进...唯一的区别在于查询处理测试的是category.id的有效性,而不是php

Improved based on hybrid between marc B and mine... Only efficiency difference is that the query handles testing the validity of categories.id instead of the php

这篇关于在编辑表单上填充复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆