从数据库中检索复选框值

时间:2014-11-02 04:11:43

标签: php mysql

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

项目表

+----------+--------------+
| item_id  |   item_name  | 
+-------------+-----------+
| 1        | A            |
| 2        | B            |
| 3        | C            |
| 4        | D            |
| 5        | E            |
+----------+--------------+

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 个答案:

答案 0 :(得分:1)

您应该使用原始复选框检查所选值,并使用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; ?>