在编辑表单上填充复选框

编程入门 行业动态 更新时间:2024-10-28 01:22:46
本文介绍了在编辑表单上填充复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

在编辑表单上填充复选框

本文发布于:2023-05-31 22:04:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/400209.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   复选框   编辑

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!