CodeIgniter数组插入仅单条生效、更新报错问题排查求助
问题排查与代码修复
1. 批量插入功能失效问题
原代码问题
redirect()放在foreach循环内部,导致插入第一条记录后立即跳转,循环终止,无法处理后续记录。- 每次循环调用单条插入
insert(),效率低下且不符合批量插入逻辑。
修复后的控制器插入部分
public function saveAbsensi() { if ($this->input->post('kirimabsen')) { $input = $this->input->post(); $batch_data = []; foreach ($input['id_siswa'] as $key => $val) { $batch_data[] = [ 'id_siswa' => $val, 'id_mapel' => $input['id_mapel'], 'id_kelas' => $input['id_kelas'], 'time_in' => time(), 'tanggal' => date("d"), 'bulan' => date("m"), 'tahun' => date("Y"), 'keterangan' => $input['keterangan'][$key] ]; } $this->guru_m->saveAbsen($batch_data); redirect('gr/absensi'); // 移到循环外,确保所有记录插入完成再跳转
修复后的模型插入方法
public function saveAbsen($batch_data) { // 支持批量插入和单条插入兼容 if (is_array($batch_data) && count($batch_data) > 0 && is_array($batch_data[0])) { return $this->db->insert_batch('absensi', $batch_data); } else { return $this->db->insert('absensi', $batch_data); } }
2. 更新功能报错问题
原代码问题
ubahabsen分支未定义$input变量,直接使用导致 "Undefined variable: Input"。- 未循环处理多条记录,
$key变量未定义导致 "Undefined variable: Key"。 - 模型
editAbsen()要求3个参数,但控制器仅传递1个,导致 "Missing argument 3"。 - 模型中
$id_siswa['']是无效语法,且仅用id_siswa作为更新条件会修改该学生所有缺勤记录,逻辑错误。
修复后的控制器更新部分
} elseif ($this->input->post('ubahabsen')) { $input = $this->input->post(); // 定义$input变量 foreach ($input['id_siswa'] as $key => $val) { // 仅传递需要更新的字段 $data = [ 'time_in' => time(), 'keterangan' => $input['keterangan'][$key] ]; // 明确更新条件:定位到学生当天该科目缺勤记录 $where = [ 'id_siswa' => $val, 'id_mapel' => $input['id_mapel'], 'id_kelas' => $input['id_kelas'], 'tanggal' => date("d"), 'bulan' => date("m"), 'tahun' => date("Y") ]; $this->guru_m->editAbsen($data, $where); } redirect('gr/absensi'); } }
修复后的模型更新方法
public function editAbsen($data, $where) { $this->db->where($where); $this->db->update('absensi', $data); return $this->db->affected_rows(); }
关键修复点总结
- 批量插入:将
redirect()移到循环外,改用insert_batch()批量提交数据。 - 更新逻辑:
- 补充
$input变量定义,循环处理多条记录。 - 调整模型参数为
$data(更新字段)和$where(定位条件),避免参数缺失错误。 - 使用多条件定位(学生ID+科目+班级+日期)确保只修改目标缺勤记录,避免误操作。
- 补充
内容的提问来源于stack exchange,提问作者William Sanders
相关产品推荐
相关产品推荐

