CodeIgniter中复选框数据无法插入SQL数据库(未存储或为NULL)
解决CodeIgniter复选框数据无法插入数据库的问题
你的代码存在几处关键错误,导致复选框数据无法正常存储,以下是修正方案:
1. 修正Model中的表单验证规则
CodeIgniter处理数组类型的表单字段时,验证规则里的field不需要加[],同时建议补充数组验证规则确保至少选择一个选项:
public function rules() { return array( array( 'field' => '_butype_', 'label' => 'Business Type', 'rules' => 'required|trim|alpha_numeric_spaces|min_length[2]|max_length[50]' ), array( 'field' => '_bumotiv_', // 移除[] 'label' => 'Motivation', 'rules' => 'required|array|min_length[1]' // 确保是数组且至少有一个元素 ), ); }
2. 修正Model中的数据插入逻辑
原代码存在语法错误(多余的$)和数组获取方式错误,CI会自动将name="_bumotiv_[]"的表单数据解析为名为_bumotiv_的数组,修正后的代码:
public function insert(){ $post = $this->input->post(); if (!empty($post)){ // 正确获取复选框数组 $bumotiv = $this->input->post('_bumotiv_'); $data = array( 'ginfo_id' => NULL, 'ginfo_butype' => htmlspecialchars($post['_butype_']), 'ginfo_bumotiv' => json_encode($bumotiv), // 移除多余的$ ); $data = $this->security->xss_clean($data); if($this->db->insert($this->table, $data)){ $response = array( 'status' => 'success', 'message' => 'Success insert data', ); } else { $response = array( 'status' => 'error', 'message' => 'Failed insert data', ); } } else { $response = array( 'status' => 'error', 'message' => 'Data not found!', ); } return $response; }
3. 修正视图中的复选框代码
set_checkbox的第一个参数应为字段基础名_bumotiv_(不带[])- 每个复选框的
id必须唯一,否则label关联会失效:
<div class="form-group row"> <label class="col-sm-3 col-form-label" style="text-align: left;">What actually motivated you to start your own business? </label> <div class="col-sm-6"> <input class="form-group" type="checkbox" name="_bumotiv_[]" id="_bumotiv_1" value="To be independent from working for other people" <?php echo set_checkbox('_bumotiv_', 'To be independent from working for other people'); ?>> <label for="_bumotiv_1">To be independent from working for other people. </label> <br> <input class="form-group" type="checkbox" name="_bumotiv_[]" id="_bumotiv_2" value="I have a bright idea that can be commercialised" <?php echo set_checkbox('_bumotiv_', 'I have a bright idea that can be commercialised'); ?>> <label for="_bumotiv_2">I have a bright idea that can be commercialised.</label> <br> </div> </div>
错误原因总结
- 表单验证规则中字段名带
[],导致CI无法正确识别字段进行验证 - 获取数组数据时的语法错误(
$$post)和键名错误(带[]) - 视图中
set_checkbox参数错误、复选框id重复,导致表单回显和交互异常
内容的提问来源于stack exchange,提问作者manalfayyad
相关产品推荐
相关产品推荐

