2014-11-02 23 views
2

我将复选框值以一对多的模式存储在中间表中。用于更新复选框值如何使用那些存储在该表上的已检查的列表填充整个列表。检索数据库中的复选框值

项目表

​​

item_tag

+----------+--------------+ 
    | item_id |  tag_id | 
    +-------------+-----------+ 
    | 1  | 1   | 
    | 1  | 2   | 
    | 2  | 1   | 
    | 2  | 2   | 
    | 2  | 3   | 
    +----------+--------------+ 

tag_table

+----------+--------------+ 
| tag_id |  tag_name | 
+-------------+-----------+ 
| 1  | foo   | 
| 2  | bar   | 
| 3  | foo1   | 
| 4  | bar1   | 
| 5  | foo2   | 
+----------+--------------+ 

回答

1

您应该检查CHEC原装复选框糟透了值,与in_array

<?php 
    // get the checked items 
    // SELECT * FROM `item_tag` WHERE `item_id` = 2 
    $checkedItems = [1, 2, 3]; 

    // get the checkboxes 
    // SELECT * FROM `tag_table` 
    $checkboxes = [1=>'foo', 2=>'bar', 3=>'foo1', 4=>'bar1', 5=>'foo2']; 
?> 


<?php foreach ($checkboxes as $index => $value): ?> 
    <input 
     type="checkbox" 
     value="<?php echo $index; ?>" 

     <?php if (in_array($index, $checkedItems)): ?> 
      checked="checked" 
     <?php endif; ?> 
    /> 
    <?php echo $value; ?> 
<?php endforeach; ?> 
+0

在第一个查询形式item_tag我为什么要选择所有,而不是仅仅TAG_ID – 2014-11-02 04:40:33

+0

@freaky_coder因为你要显示所有** **复选框给用户,允许用户改变它们。 – dashtinejad 2014-11-02 04:43:18

+0

检索的值不被检查。 – 2014-11-02 05:33:17