doujing1156 2010-11-13 15:50
浏览 19
已采纳

循环时将查询与PHP进行比较

Here is my table setup:

  • employee: Employee information, name, address, etc...
  • group: List of distribution groups.
  • employee2group: table that links employees to multiple groups.

I have it setup this way so I can add groups in the future, without having to add columns to my employee table. This may seem like common sense to you all, but I just started with PHP a couple months ago, so everything is still new and confusing to me.

So, I'm working on my update form, which will display a list of check boxes that is populated with a simple SELECT * FROM group query. The idea is to show the ones that an employee is part of as "checked" when I view the employee in the update form.

Currently, my while loop to show the list of check boxes is this:

<?php
 $group_list_query = "SELECT * FROM group"
 $group_list_result = mysql_query($group_list_query, $cmsWrite)
 while ($row = mysql_fetch_assoc($group_list_result)) {
  echo "<input type=\"checkbox\" name=\"distro_{$row['group_name']}\"> {$row['group_name']}";
 }
?>

Pretty simple. I might have some syntax errors in there, but in my code they don't exist, because it works fine.

So what I need to do, is run another query that returns ONLY the names of the groups that the employee belongs to:

SELECT group.group_name 
FROM group JOIN employee2group ON group.group_id = employee2group.group_id 
WHERE employee2group.employee_id ='{$_GET['employee_id']}'

Then, I need to compare the two queries, and output a normal check box when there isn't a match, and output a checked check box when there is a match.

I tried doing a while statement that set $row = query1 and $row2 = query2, and compare the $row and $row2 values, but then it only returned instances where both queries had results, instead of all of them.

I hope this makes sense, I've been trolling the internet for a while, and haven't found anything that pertains to my problem.

Thanks for reading!

  • 写回答

1条回答 默认 最新

  • dongsheng6056 2010-11-13 15:59
    关注

    Two solutions :

    1 : Get a array of the groupIds that user is a member of, then when looping through the group list. Check if the id is in that array with in_array, if it is dont display the check box

    2 : Do a left join on the employee2group table and check if the value = null or not, if its null display the check box.

    --

    Off question topic but you should also look at using bound paramaters rather than just including them inthe sql statement like that, leaves it open to sql injection otherwise.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程