【问题标题】:How to fix Trying to access array offset on value of type null error如何修复尝试访问空类型值的数组偏移量错误
【发布时间】:2021-04-26 17:00:40
【问题描述】:

我正在使用 PHP 创建一个时间表视图,其中我正在根据日期和时间获取讲座数据。

这是我做的代码

$monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
$result_11to1 = mysqli_query($con, $monday_lectures);
$m11to1 = mysqli_fetch_array($result_11to1);
if ($m11to1["lecture_day"] == !'') {
    echo "<td>".$m11to1["lecture_name"]."</td>";
} else {
    echo "<td> no class</td>";
}

但上面的代码出现以下错误:

警告:尝试访问第 45 行 C:\xampp\htdocs\nexgschool\admin\notify\add_time_table.php 中 null 类型值的数组偏移量

【问题讨论】:

    标签: php arrays mysqli


    【解决方案1】:

    当您在从数据库获取数据后收到此错误时,这意味着数据库没有找到任何匹配的行。当没有匹配的记录或结果集已用完时,大多数数据库获取函数返回null 或空数组。

    要解决问题,您需要检查值的真实性或要访问的密钥是否存在。

    $monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
    $result_11to1 = mysqli_query($con, $monday_lectures);
    $m11to1 = mysqli_fetch_array($result_11to1);
    if ($m11to1 && $m11to1["lecture_day"] == !'') {
        echo "<td>".$m11to1["lecture_name"]."</td>";
    } else {
        echo "<td> no class</td>";
    }
    

    如果您所追求的是结果数组中的单个值,那么您可以指定一个默认值以防结果不存在。

    $monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
    $result_11to1 = mysqli_query($con, $monday_lectures);
    $m11to1 = mysqli_fetch_array($result_11to1);
    $lecture = $m11to1["lecture_day"] ?? null;
    

    这同样适用于 PDO。

    $monday_lectures = $pdo->prepare("SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'");
    $monday_lectures->execute();
    $m11to1 = $monday_lectures->fetch();
    $lecture = $m11to1["lecture_day"] ?? null;
    

    【讨论】:

      猜你喜欢
      • 2020-07-29
      • 2023-02-23
      • 1970-01-01
      • 2021-07-23
      • 2020-05-20
      • 1970-01-01
      相关资源
      最近更新 更多