【问题标题】:Received Error: "PHP Warning: Trying to access array offset on value of type null", but correct value returned [duplicate]收到错误:“PHP 警告:尝试访问 null 类型值的数组偏移量”,但返回正确的值 [重复]
【发布时间】:2022-01-25 17:26:22
【问题描述】:

我确实研究了其他类似问题的线程,但我的情况似乎很独特。我正在使用我创建的 PHP 函数根据“WHERE”子句中的两个参数在表中查找单行。使用该函数时,生成的HTML正是我所期望的,并且数据是从这个函数中填写的,但是我仍然得到一个PHP错误:

“PHP 警告:尝试访问第 66 行 /var/www/html/functions/resolve_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
  • 洛基 Linux 8.5

【问题讨论】:

  • 它在代码中作为注释。它说,“这是第 66 行”

标签: php


【解决方案1】:

如果查询没有发现任何内容,则此代码将发出警告,因为$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;

【讨论】:

  • Alex,这解决了我的问题,你的解释很有道理。感谢您的洞察力和建议!
猜你喜欢
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 2021-03-31
  • 2022-10-16
  • 2021-07-23
相关资源
最近更新 更多