收到错误:"PHP Warning: Trying to access array offset on value of type null",但返回了正确的值



我确实研究了其他类似问题的线程,但我的情况似乎是独一无二的。我正在使用我创建的PHP函数,该函数基于";其中";条款当使用该函数时,得到的HTML正是我所期望的,并且数据是从该函数中填充的,但我仍然得到一个PHP错误:

"PHP警告:试图访问第66行/var/www/html/functions/resole_functions.PHP中null类型值的数组偏移量";

这是我的功能:


function resolve_feature_device($feature, $device) {
$conn = db_connect();  // Connect to the configurator database

// Build the query to retrieve the partnum based on the feature provided
$result = $conn->query("SELECT txt_partnum
FROM tbl_device_feature
WHERE txt_feature='$feature'
AND txt_partnum='$device';");

// If the result is false, return false to the calling procedure, else return the resulting value
if (!$result) {
return false;
} else {
$row = $result->fetch_assoc();
$device = $row["txt_partnum"];  // This is line 66
if (isset($device)) {
return $device;
} else {
return false;
}
}
}

数据库表是零件号和特征的列表,因此有多行具有相同的零件号,也有多行带有相同的特征,但应该只有一个唯一的行同时具有特定的零件号和特定的特征。

我不明白为什么这个函数为我提供了预期的输出,但仍然给出了PHP错误消息。输出显然不是";空";。如有任何指导,我们将不胜感激。

  • PHP 8.1.1
  • Apache 2.4.37
  • MariaDB 10.3.28
  • Rocky Linux 8.5

如果查询一无所获,则此代码将发出该警告,因为$row为空,并且您正明确尝试从中提取值,而在之后,您将检查它是否已设置:

$device = $row["txt_partnum"];
if (isset($device)) {
return $device;
} else {
return false;
}

您想要对可能未设置的东西调用isset(),而不是您刚刚显式创建的东西:

if (isset($row["txt_partnum"])) {
return $row["txt_partnum"];
} else {
return false;
}

或者,只需:

return $row["txt_partnum"] ?? false;

最新更新