我有一个(MySQL)数据库表,如下所示:
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;
我想在此表中显示并保存所有行作为复选框 如果选中,则将web_only标记为1,未选中将web_only标记为0。
显示它们很简单:
<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>
但是我应该如何处理保存此复选框列表?
我可以使用$_POST['category']
访问所有这些内容,但这只会$_POST
选中的复选框?
要回答我自己的问题,我可以将整个表web_only字段更新为0,然后将已发布的结果预先更新为1,假设所有未包含的内容都未选中。
SQL:UPDATE dm_webcategory SET web_only = 0
然后PHP:
foreach($this->input->post('category') as $category)
{
$this->db->update('dm_webcategory', array('web_only' => '1'), array('cat_id' => $category));
}
上述情况并非安全&#39;不过,还有更好的方法吗?当我没有显示/保存表格中的每一行时,情况怎么样?
答案 0 :(得分:1)
试试这个。
HTML:
<form method="post" action="">
<?php foreach($categories as $category): ?>
<input type="hidden" name="category[<?php echo $category->cat_id;?>]" value="0"/>
<input type="checkbox" name="category[<?php echo $category->cat_id;?>]" value="1" <?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>
PHP:
foreach($this->input->post('category') as $id => $value)
{
$this->db->update('dm_webcategory', array('web_only' => $value), array('cat_id' => $id));
}
答案 1 :(得分:1)
请尝试以下表单:
<form method="post" action="">
<?php foreach($categories as $category): ?>
<input type="hidden" name="category[<?php echo $category->cat_id;?>]" value="0" />
<input type="checkbox" name="category[<?php echo $category->cat_id;?>]" value="1" <?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>
然后:
foreach($this->input->post('category') as $cat_id => $web_only)
{
$this->db->update('dm_webcategory', array('web_only' => $web_only), array('cat_id' => $cat_id));
}
答案 2 :(得分:0)
您尝试使用以下代码
控制器代码
$array = $this->input->post('s2');
$data['subject'] = implode(',',$array);
$this->student_model->saveForm($data);
查看代码
<form method="post" action="">
Categories :
<?php foreach($categories as $category): ?>
<input type="checkbox" name="s2[]" value="<?php echo $category->cat_id;?>">English
<?php endforeach; ?>
<input type="submit" class="btn btn-primary" value="Save" />
<br>
</form>
模型
$this->db->insert('Tablename', $data);