
本文详解 CodeIgniter 中更新轮播图记录时的图片替换逻辑,重点解决因查询失败导致的 Trying to get property 'gambar' of non-object 错误,并提供健壮的文件删除、上传与数据库更新全流程实现。
本文详解 codeigniter 中更新轮播图记录时的图片替换逻辑,重点解决因查询失败导致的 `trying to get property 'gambar' of non-object` 错误,并提供健壮的文件删除、上传与数据库更新全流程实现。
在使用 CodeIgniter 实现轮播图(Carousel)数据更新功能时,常见错误 Severity: Notice — Trying to get property 'gambar' of non-object 本质是 $this->modelcarousel->getDataById($id)->row() 返回了 NULL(即未查到对应 ID 的记录),却直接调用 $data->gambar,引发 PHP Notice。这不仅影响程序健壮性,还可能导致后续文件操作失败或安全风险。
✅ 正确做法:添加空值校验与异常处理
首先,必须确保数据库查询成功且结果存在:
public function edit_carousel()
{
$id = $this->input->post('id_carousel');
// ✅ 关键:检查查询结果是否有效
$query = $this->modelcarousel->getDataById($id);
if ($query->num_rows() === 0) {
$this->session->set_flashdata('error', '找不到 ID 为 ' . $id . ' 的轮播图记录');
redirect('carousel');
return;
}
$data = $query->row();
$old_image_path = './assets/foto/carousel/' . $data->gambar;
// ✅ 安全删除旧图片(仅当文件存在且可读时)
if (!empty($data->gambar) && is_readable($old_image_path)) {
unlink($old_image_path);
}
// ✅ 配置上传库(注意:无需重复 load + initialize,upload 库支持单次配置)
$config = [
'upload_path' => './assets/foto/carousel',
'allowed_types' => 'gif|jpg|png|jpeg',
'max_size' => 2048,
'encrypt_name' => TRUE, // 推荐开启,避免文件名冲突/覆盖
'remove_spaces' => TRUE
];
$this->load->library('upload', $config);
// ✅ 执行上传
if (!$this->upload->do_upload('gambar')) {
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('carousel/edit/' . $id); // 返回编辑页并提示错误
return;
}
// ✅ 获取上传后的文件信息(注意:$this->upload->data() 返回数组,需取 'file_name')
$upload_data = $this->upload->data();
$new_image_name = $upload_data['file_name'];
// ✅ 构建更新数据(只存文件名,非完整路径)
$update_data = [
'gambar' => $new_image_name,
'headline' => $this->input->post('headline'),
'deskripsi' => $this->input->post('deskripsi'),
'status' => $this->input->post('status'),
'tanggal_post' => $this->input->post('tanggal_post')
];
// ✅ 执行更新
if ($this->modelcarousel->update_carousel($id, $update_data)) {
$this->session->set_flashdata('success', '轮播图更新成功!');
redirect('carousel');
} else {
$this->session->set_flashdata('error', '数据库更新失败,请重试');
redirect('carousel/edit/' . $id);
}
}? 补充说明与最佳实践
- Model 层无需修改:你提供的 getDataById() 和 update_carousel() 方法逻辑正确,但建议在 getDataById() 中添加 ->row() 调用前的判空日志(开发阶段);
- encrypt_name => TRUE 可防止恶意文件名(如 ../../shell.php)造成路径穿越,提升安全性;
- 始终使用 session->flashdata() 替代 echo 或裸 redirect(),提供用户友好反馈;
- 前端表单务必包含 enctype="multipart/form-data",否则 $_FILES 将为空;
- 若图片字段允许为空(即不强制更新图片),应在控制器中判断 $_FILES['gambar']['name'] 是否非空,决定是否执行上传流程。
通过以上重构,你的轮播图更新功能将具备完整的错误防御能力、清晰的用户反馈机制和符合生产环境要求的代码健壮性。


















