You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决PHP预处理语句报错Trying to access array offset on value of type null

问题原因

Trying to access array offset on value of type null 报错的核心原因是:当传入的$status在application表中没有匹配的记录时,fetch_row()方法会返回null,此时直接访问[0]数组偏移量就会触发对应报错。
你删除[0]后输出None,是因为此时$MostServiceRequested是数组类型,和字符串做相等判断永远不成立,最终会走到else分支。


修复方案

调整PHP代码,先判断查询是否返回有效结果再取值即可:

$stmt4 = $mysqli->prepare("SELECT ServiceRequested,status, COUNT(ServiceRequested) AS `occurrence` FROM application WHERE status = ? GROUP BY ServiceRequested ORDER BY `occurrence` DESC LIMIT 1");
$stmt4->bind_param('i',$status);
$stmt4->execute();
$result = $stmt4->get_result();
$row = $result->fetch_row();
// 先判空再取值
$MostServiceRequested = $row ? $row[0] : '';

if ($MostServiceRequested == 'ABC'){
    $ServiceRequested = 'ABC';
} elseif ($MostServiceRequested == 'DEF'){
    $ServiceRequested = 'DEF';
} elseif ($MostServiceRequested == 'GHI'){
    $ServiceRequested = 'GHI';
} else {
    $ServiceRequested = 'None';
}

原有前端输出代码无需修改:

<h3><?php echo $ServiceRequested; ?></h3>

可选优化

你可以把分支判断替换为数组匹配,代码更简洁易维护:

$validServices = ['ABC' => 'ABC', 'DEF' => 'DEF', 'GHI' => 'GHI'];
$ServiceRequested = $validServices[$MostServiceRequested] ?? 'None';

内容的提问来源于stack exchange,提问作者Laan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:27:05