How to solve error: Trying to access array offset on value of type null with Prepared Statement PHP

How to solve error: Trying to access array offset on value of type null with Prepared Statement PHP

我正在尝试显示请求的整体服务。但我一直收到错误

Trying to access array offset on value of type null

SQL 语句有效,但我不确定 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();
$MostServiceRequested = $stmt4->get_result()->fetch_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>

我尝试删除 $MostServiceRequested = $stmt4->get_result()->fetch_row()[0] 中的 [0]; 但它显示 None 即使数据库中有记录。我能知道代码需要修复什么或如何修复吗?

如果您只想要查询的结果或“None”(如果没有返回行),试试这个...

$sql = <<<_SQL
SELECT ServiceRequested, COUNT(ServiceRequested) AS `occurrence`
FROM application
WHERE status = ?
GROUP BY ServiceRequested
ORDER BY `occurrence` DESC LIMIT 1
_SQL;

$stmt4 = $mysqli->prepare($sql);
$stmt4->bind_param('i', $status);
$stmt4->execute();
$ServiceRequested = $stmt4->get_result()->fetch_row()[0] ?? "None";

您也不应该在 SELECT 子句中包含 status 而未将其包含在 GROUP BY 中。

null coalescing operator (??) 需要PHP 7.0