Reputation:
I am storing checkbox values in a intermediate table in a one-to-many pattern. for updating the checkbox values how to populate the whole list with those checked which are stored on that table.
item table
+----------+--------------+
| 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 |
+----------+--------------+
Upvotes: 2
Views: 111
Reputation: 6253
You should check your checked values with original checkboxes, with 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; ?>
Upvotes: 1