2014-11-02 60 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