I have a (MySQL) database table that looks like:
CREATE TABLE `dm_webcategory` (
`cat_id` int(10) DEFAULT NULL,
`PUB_CATEGORY` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`web_only` tinyint(1) DEFAULT '0',
UNIQUE KEY `dm_webcategory_pk` (`cat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I want to display and save ALL rows in this table as checkboxes If checked, will mark web_only as 1, and unchecked will mark web_only as 0.
Displaying them is simple:
<form method="post" action="">
<?php foreach($categories as $category): ?>
<input type="checkbox" name="category[]" value="<?php echo $category->cat_id;?>" <?php if($category->web_only) echo "checked"; ?> /> <?php echo $category->PUB_CATEGORY;?>
<?php endforeach; ?>
<input type="submit" class="btn btn-primary" value="Save" />
<br>
</form>
But how should I go about saving this list of checkboxes?
I can access all of them using $_POST['category']
, but this will only $_POST
the checked boxes?
To answer my own question, I could update the whole table web_only field to 0, and then foreach the posted result to update individually to 1, assuming all those not included were unchecked.
SQL: UPDATE dm_webcategory SET web_only = 0
Then PHP:
foreach($this->input->post('category') as $category)
{
$this->db->update('dm_webcategory', array('web_only' => '1'), array('cat_id' => $category));
}
The above doesn't feel very 'safe' though, is there a better way? What about the scenario when I wasn't displaying / saving every row in the table?