2013-07-19 36 views
0

我有两个表我需要加入,并且需要检查重复区域的html复选框,如果contact_id字段在列表中。mysql表加入和重复区域的复选框

表一 “contact_to_category” - ID,CONTACT_ID和CATEGORY_ID

表二 “类” - CATEGORY_ID,类别,状态

我想创建联系人的更新页面,显示表2中的所有类别,如果客户端contact_id在表1中,则选中该复选框。通过这种方式,编辑人员可以查看哪些类别已经生效。

这是我已经尝试过,但不知道如何检查复选框,如果他们的ID列在表一吗?我尝试过连接,但没有变量来表示如果a = b,然后在复选框的重复区域中回显“checked”。

谢谢!

$query_flags = "SELECT a.category, a.status, a.category_id FROM category a LEFT JOIN contact_to_category ON contact_to_category.category_id = a.category_id AND contact_to_category.contact_id = '$contactid' AND a.status = 1"; 

     <?php do { ?> 
      <table width="327" border="0" cellspacing="0" cellpadding="1"> 
      <tr> 
       <td width="20" align="right"><input name="catlist[]" type="checkbox" id="catlist[]" value="<?php echo $row_flags['category_id']; ?>" /> 
       <label for="catlist[]"></label></td> 
       <td width="226"><?php echo $row_flags['category']; ?></td> 
      </tr> 
      </table> 
      <?php } while ($row_flags = mysql_fetch_assoc($flags)); ?> 
+0

无论如何使用while!为什么? 。先得到结果并检查它 – zod

回答

0

你正在做一个LEFT JOIN当CATEGORY_ID不是第一个表会有空行,所以这是你怎么能检查您的复选框我从第一台contact_to_category.category_id AS second_cat_id添加一列,检查是否它是否存在

$query_flags = "SELECT a.category, a.status, a.category_id 
,contact_to_category.category_id AS second_cat_id FROM category a 
LEFT JOIN contact_to_category ON contact_to_category.category_id = a.category_id 
AND contact_to_category.contact_id = '$contactid' AND a.status = 1"; 
$row_flags=mysql_query($query_flags); i assume you have done this in your code 
     <?php do { ?> 
      <table width="327" border="0" cellspacing="0" cellpadding="1"> 
      <tr> 
       <td width="20" align="right"> 
    <?php if(!empty($row_flags['second_cat_id '])){ ?> 

<input name="catlist[]" type="checkbox" checked="checked" id="catlist[]" value="<?php echo $row_flags['category_id']; ?>" /> 
    <?php } else{?> 
<input name="catlist[]" type="checkbox" id="catlist[]" value="<?php echo $row_flags['category_id']; ?>" /> 
    <?php } ?> 
       <label for="catlist[]"></label></td> 
       <td width="226"><?php echo $row_flags['category']; ?></td> 
      </tr> 
      </table> 
      <?php } while ($row_flags = mysql_fetch_assoc($flags)); ?> 
+0

这太棒了!我一直在想这件事......开始时不工作,但看到'second_cat_id'中的额外空间就像一个魅力!谢谢,我刚刚学到了新东西! – user2087269