CodeIgniter 3 查询未返回 null 或 0 的原因及正确写法
技术百科
聖光之護
发布时间:2026-01-13
浏览: 次 当 codeigniter 3 查询无匹配记录时,`row()->sold_price` 会触发 php 致命错误(因访问 null 对象属性),而非返回 0 或 null;根本原因是链式调用缺乏空值保护,且 `where()` 多参数误用导致 sql 条件拼接错误。
在 CodeIgniter 3 中,$this->db->where() 方法不支持单次调用传入多个条件字段(如你原代码中 ->where('category_ID', $caid,'sold_date >=',$prev_year_start_month,...))。这种写法会导致 CI 忽略后续参数,仅执行第一个 where('category_ID', $caid),其余日期条件被丢弃——这正是查询“跨年拉取数据”的根源:缺少日期过滤,数据库返回了其他年份的任意匹配记录。
✅ 正确做法是将每个 WHERE 条件拆分为独立的 where() 调用,或使用字符串形式的复合条件:
// ✅ 推荐:清晰、安全、符合 CI 最佳实践
$query = $this->db->select_sum('sold_price')
->from('tbl_sales')
->where('category_ID', $caid)
->where('sold_date >=', $prev_year_start_month)
->where('sold_date <=', $prev_year_end_month)
->group_by('category_ID')
->get();
$result = $query->row();
$sold_price = ($result && isset($result->sold_price)) ? (float)$result->sold_price : 0.0;⚠️ 注意事项:
- 永远不要直接调用 ->row()->xxx:若查询无结果,row() 返回 null,再访问 ->sold_price 将抛出 Trying to get property 'sold_price' of non-object 错误;
- 使用 isset() 或三元判断确保对象存在;
- 日期字段(如 sold_date)需确保数据库中为 DATE 或 DATETIME 类型,且 $prev_year_start_month、$prev_year_end_month 格式为 'Y-m-d'(如 '2025-01-01'),避免隐式类型转换;
- 若需兼容无分组场景(如单条记录),可改用 ->row_array() + array_key_exists() 增强健壮性;
- 避免拼接 SQL 字符串(如第二种答案中的 "category_I
D= $caid AND..."),易引发 SQL 注入,除非 $caid 和日期变量已严格过滤(强烈不推荐)。
? 进阶建议:封装为可复用方法,自动处理空值与类型转换:
protected function getSumByDateRange($table, $sum_field, $where_conditions = [], $date_field = 'sold_date', $start = '', $end = '') {
$this->db->select_sum($sum_field);
$this->db->from($table);
foreach ($where_conditions as $key => $value) {
$this->db->where($key, $value);
}
if (!empty($start) && !empty($end)) {
$this->db->where("{$date_field} >= ", $start);
$this->db->where("{$date_field} <= ", $end);
}
$row = $this->db->get()->row();
return $row ? (float)($row->$sum_field ?? 0) : 0.0;
}
// 调用示例
$total = $this->getSumByDateRange(
'tbl_sales',
'sold_price',
['category_ID' => $caid],
'sold_date',
$prev_year_start_month,
$prev_year_end_month
);通过规范 where() 用法 + 主动判空,即可彻底解决“本该返回 0 却报错或返回错误数据”的问题,保障查询逻辑的准确性和系统稳定性。
# ai
# 多个
# 第一个
# 链式
# 进阶
# 而非
# 第二种
# 不支持
# go
# 对象
# Property
# 字符串
# 数据库
# 报错
# this
# NULL
# 封装
# 抛出
# php
# 隐式类型转换
# 类型转换
# Object
# sql
# date
# 如你
相关栏目:
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
AI推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
SEO优化<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
技术百科<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
谷歌推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
百度推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
网络营销<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
案例网站<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
精选文章<?muma echo $count; ?>
】
相关推荐
- win11如何清理传递优化文件 Win11为C盘瘦
- 如何使用Golang实现路由分组管理_Golang
- Windows10无法连接到Internet_Wi
- PythonFastAPI项目实战教程_API接口
- Win11怎么设置ip地址_Windows 11手
- 如何在 Django 中安全修改用户密码而不使会话
- Win11怎么设置系统还原_Windows11系统
- php订单日志怎么导出excel_php导出订单日
- phpstudy本地环境mysql忘记密码_重置m
- Python集合操作技巧_高效去重解析【教程】
- Python大文件处理策略_内存优化说明【指导】
- Go 中 defer 语句在 goroutine
- Win10怎么卸载爱奇艺_Win10彻底卸载爱奇艺
- c# 如何用c#实现一个支持优先级的任务队列
- php错误怎么开启_display_errors与
- PHP中require语句后直接调用返回对象方法的
- Python字符串处理进阶_切片方法解析【指导】
- 如何使用Golang捕获并记录协程panic_保证
- Win11键盘快捷键大全_Windows 11常用
- Python正则表达式实战_模式匹配说明【教程】
- Python性能剖析高级教程_cProfileLi
- Python异步网络编程_aiohttp说明【指导
- Windows 10怎么录屏_Windows 10
- php报错怎么查看_定位PHP致命错误与警告的方法
- php订单日志怎么按金额排序_php按订单金额排序
- 如何在Mac上搭建Golang开发环境_使用Hom
- Windows10怎么查看系统激活状态_Windo
- Mac电脑如何恢复出厂设置_Mac抹掉数据并重装系
- 如何使用Golang实现Web表单数据绑定_自动映
- 如何使用Golang反射将map转换为struct
- Windows 11登录时提示“用户配置文件服务登
- MAC怎么设置程序窗口永远最前_MAC窗口置顶插件
- 如何在Golang中使用log包输出不同级别日志_
- c++如何使用std::bitset进行位图算法_
- Python与GPU加速技术_CUDA与Numba
- LINUX如何删除用户和用户组_Linux use
- 小程序里php怎么变mp4_小程序调用php生成m
- Win11怎么设置指纹解锁 Win11笔记本录入指
- Win11怎么连接蓝牙耳机_Win11蓝牙设备配对
- Win11怎么设置环境变量_Win11配置Path
- Python网络日志追踪_请求定位解析【教程】
- php修改数据怎么批量改状态_批量更新status
- 为什么Go建议使用error接口作为错误返回_Go
- c++怎么用jemalloc c++替换默认内存分
- 如何使用Golang template生成文本模板
- Win11怎么关闭贴靠布局_Win11禁用窗口最大
- 如何用正则表达式精确匹配“start”到“end”
- C#怎么使用委托和事件 C# delegate与e
- 如何使用Golang开发简单的聊天室消息存储_Go
- Windows10如何更改桌面背景_Win10个性

D= $caid AND..."),易引发 SQL 注入,除非 $caid 和日期变量已严格过滤(强烈不推荐)。
QQ客服