CodeIgniter更新轮播图报gambar属性非对象错误排查
CodeIgniter轮播图更新功能报错修复
报错信息
运行轮播图更新接口时抛出Notice级别错误:
Severity: Notice
Message: Trying to get property 'gambar' of non-object
Filename: admin/CarouselController.php
Line Number: 42
问题根因定位
报错触发点为控制器第42行代码$gambar = './assets/foto/carousel/'.$data->gambar;,该错误表示$data不是有效对象,无法访问其gambar属性,具体诱因如下:
- 参数校验缺失:前端提交的
id_carousel参数为空、或者传入了数据库中不存在的轮播图ID时,getDataById($id)->row()查询无结果,返回空值而非预期的记录对象 - 逻辑顺序错误:原代码将旧文件删除成功作为后续上传、更新操作的前置判断条件,只要旧图不存在、或者没有文件删除权限,整个更新流程会直接终止
- 字段赋值错误:上传成功后直接将
$this->upload->data()返回的完整文件信息数组赋值给gambar字段,但数据库gambar字段为字符串类型,仅需要存储文件名,直接传入数组会导致数据库写入失败
修复方案
现有模型层代码逻辑正确,仅需要调整控制器层edit_carousel方法即可,修复后代码如下:
public function edit_carousel(){//update carousel // 校验轮播图ID参数 $id = $this->input->post('id_carousel'); if(empty($id)){ echo '参数错误:未获取到轮播图ID'; return; } // 查询旧轮播图数据,判断记录是否存在 $old_data = $this->modelcarousel->getDataById($id)->row(); if(empty($old_data)){ echo '参数错误:对应轮播图记录不存在'; return; } // 初始化文件上传配置 $config['upload_path'] = './assets/foto/carousel'; $config['allowed_types'] = 'gif|jpg|png|jpeg'; $config['max_size'] = 2048; $config['max_width'] = 10000000; $config['max_height'] = 10000000; $this->load->library('upload', $config); $this->upload->initialize($config); // 预填充非图片类更新字段 $update_data = array( 'headline' => $this->input->post('headline'), 'deskripsi' => $this->input->post('deskripsi'), 'status' => $this->input->post('status'), 'tanggal_post' => $this->input->post('tanggal_post') ); // 处理图片上传逻辑 if($this->upload->do_upload('gambar')){ // 上传成功仅提取文件名存入数据库 $upload_info = $this->upload->data(); $update_data['gambar'] = $upload_info['file_name']; // 删除服务器上的旧轮播图 $old_gambar_path = './assets/foto/carousel/'.$old_data->gambar; if(file_exists($old_gambar_path) && is_readable($old_gambar_path)){ unlink($old_gambar_path); } }else{ // 未选择新图时保留旧图,其他上传错误直接抛出提示 $upload_error = $this->upload->display_errors(); if(strpos($upload_error, 'You did not select a file to upload') === false){ echo '图片上传失败:'.$upload_error; return; } } // 执行数据库更新 $update = $this->modelcarousel->update_carousel($id,$update_data); if ($update) { redirect('carousel'); }else{ echo '更新失败'; } }
修复点说明
- 新增ID参数校验、数据存在性校验,从根源避免查询结果为空时访问对象属性的报错
- 调整逻辑执行顺序,不再将旧图删除成功作为更新操作的前置条件,兼容旧图丢失场景
- 修复图片字段赋值错误,仅将上传后的文件名写入数据库
- 兼容未上传新图的编辑场景:用户不重新选择图片时,保留原有轮播图文件,不阻断更新流程
- 旧图删除逻辑增加文件存在判断,避免文件系统操作报错
内容的提问来源于stack exchange,提问作者Firdan Mahendra Wardana
相关产品推荐
相关产品推荐

