CodeIgniter中如何将复选框选中数存入数据库并按ID展示
解决CodeIgniter中按特定ID对应展示复选框统计数量的问题
没问题,我来帮你一步步搞定这个需求!你现在的代码已经能把复选框数量存入数据库,但缺少和特定ID的关联,所以我们需要调整几个地方:
1. 先调整数据库表结构
首先,你的employees表需要新增一个字段来存储那个"特定ID"(比如用户ID、任务ID之类的,根据你的业务场景命名,比如叫target_id),类型建议用INT,最好加上索引方便查询。
2. 修改插入逻辑,关联特定ID
现在你提交表单的时候,需要把那个特定ID也传递过来——可以用表单隐藏域,或者从会话(比如登录用户ID)里获取。比如表单里加个隐藏域:
<input type="hidden" name="target_id" value="<?php echo $your_specific_id; ?>">
然后修改模型里的插入代码,把特定ID和统计数量一起存入:
// 获取复选框数量 $count = count($this->input->post('checkbox')); // 获取特定ID(这里假设从表单提交,你也可以从会话取,比如$this->session->userdata('user_id')) $target_id = $this->input->post('target_id'); // 组装要插入的数据 $data = array( 'count' => $count, 'target_id' => $target_id // 新增的关联字段 ); // 插入数据库 $this->db->insert('employees', $data);
如果同一个特定ID可能多次提交,建议改成"存在则更新,不存在则插入",避免重复数据:
$target_id = $this->input->post('target_id'); $count = count($this->input->post('checkbox')); // 检查该ID是否已有记录 $has_record = $this->db->where('target_id', $target_id)->get('employees')->num_rows() > 0; if ($has_record) { // 更新现有记录的count值 $this->db->where('target_id', $target_id); $this->db->update('employees', array('count' => $count)); } else { // 插入新记录 $data = array( 'count' => $count, 'target_id' => $target_id ); $this->db->insert('employees', $data); }
3. 编写查询方法,按ID获取统计数
在你的模型里新增一个方法,用来根据特定ID查询对应的count:
public function get_count_by_id($target_id) { $this->db->select('count'); $this->db->where('target_id', $target_id); $query = $this->db->get('employees'); // 如果有记录就返回count,否则返回0(根据你的需求调整默认值) return $query->num_rows() > 0 ? $query->row()->count : 0; }
4. 控制器传递数据到视图
在控制器里调用上面的模型方法,获取对应ID的统计数,再传给视图:
public function display_count() { // 这里的$target_id可以从URL参数取(比如$this->uri->segment(3)),或者会话、表单获取 $target_id = 123; // 替换成你实际的特定ID // 调用模型方法获取数量 $display_count = $this->your_model_name->get_count_by_id($target_id); // 传递给视图 $data['display_count'] = $display_count; $this->load->view('your_view_file', $data); }
5. 视图中展示数量
最后在视图里直接输出传递过来的变量就行:
<div> <h3>对应ID的复选框选中数量:</h3> <p><?php echo $display_count; ?></p> </div>
这样就能实现按特定ID对应展示统计数量啦!如果还有其他细节(比如ID的传递方式、业务场景特殊需求),可以随时调整~
内容的提问来源于stack exchange,提问作者INAKOTI SANTHOSHI MATHA
相关产品推荐
相关产品推荐

