CodeIgniter控制器警告:尝试访问null值的数组偏移量,求解决方案
问题分析
错误提示翻译:严重程度:警告 消息:尝试访问类型为null的值的数组偏移量
问题出在第28行代码:$this->admin->get('barang',['id_barang' => $input])['stok']。当提交的barang_id在数据库中无匹配记录时,$this->admin->get()方法会返回null,此时直接访问['stok']数组偏移量就会触发该警告。
同时当前代码逻辑存在漏洞:表单验证规则还未执行校验,就直接读取POST参数执行数据库查询,即便barang_id为空或无效,仍会触发查询操作,进一步增加报错概率。
解决方案
方案一:快速修复(增加查询结果校验)
修改代码,先判断查询结果是否存在,再获取库存值:
private function _validasi() { $this->form_validation->set_rules('tanggal_keluar', 'Tanggal Keluar', 'required|trim'); $this->form_validation->set_rules('barang_id', 'Barang', 'required'); $input = $this->input->post('barang_id', true); // 先查询商品并判断是否存在 $barang = $this->admin->get('barang',['id_barang' => $input]); if (!$barang) { // 设置错误提示并终止验证 $this->form_validation->set_message('jumlah_keluar', '所选商品不存在'); return; } $stok = $barang['stok']; $stok_valid = $stok + 1; $this->form_validation->set_rules( 'jumlah_keluar', 'Jumlah Keluar', "required|trim|numeric|greater_than[0]|less_than[{$stok_valid}]", [ 'less_than' => "Jumlah Keluar tidak boleh lebih dari {$stok}" ] ); }
方案二:自定义验证回调(推荐,符合CodeIgniter规范)
将商品存在性校验和库存校验封装为自定义回调,确保验证顺序合理:
private function _validasi() { $this->form_validation->set_rules('tanggal_keluar', 'Tanggal Keluar', 'required|trim'); // 先验证商品是否存在 $this->form_validation->set_rules('barang_id', 'Barang', 'required|callback_check_barang_valid'); // 再验证库存是否足够 $this->form_validation->set_rules( 'jumlah_keluar', 'Jumlah Keluar', 'required|trim|numeric|greater_than[0]|callback_check_stok_cukup', [ 'greater_than' => "Jumlah Keluar必须大于0", 'required' => "请输入出库数量" ] ); } // 自定义回调:检查商品是否存在 public function check_barang_valid($barang_id) { $barang = $this->admin->get('barang', ['id_barang' => $barang_id]); if (!$barang) { $this->form_validation->set_message('check_barang_valid', '所选商品不存在于数据库中'); return false; } // 将商品数据暂存到类属性,供库存校验使用 $this->barang_terpilih = $barang; return true; } // 自定义回调:检查库存是否足够 public function check_stok_cukup($jumlah_keluar) { if (!isset($this->barang_terpilih)) { return false; } $stok = $this->barang_terpilih['stok']; if ($jumlah_keluar > $stok) { $this->form_validation->set_message('check_stok_cukup', "出库数量不能超过当前库存 {$stok}"); return false; } return true; }
额外建议
- 确认
$this->admin->get()方法的返回逻辑:如果查询不到数据,是否返回null?如果是,上述判断逻辑有效;如果返回空数组,!$barang同样能生效。 - 在控制器中调用
_validasi()后,记得通过$this->form_validation->run()判断验证是否通过,再执行后续业务逻辑。
内容的提问来源于stack exchange,提问作者Ujang Aripin
相关产品推荐
相关产品推荐

