如何修复尝试访问类型为空值的数组偏移量错误 [英] How to fix Trying to access array offset on value of type null error

查看:21
本文介绍了如何修复尝试访问类型为空值的数组偏移量错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a time table view using PHP, in which I am getting the lecture data according to the day and time.

这是我做的代码

$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>";
}

但是我在上面的代码中遇到以下错误:

But I am getting below error for the above code:

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

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\nexgschool\admin\notify\add_time_table.php on line 45

推荐答案

如果您在从数据库中获取数据后收到此错误,则表示数据库没有找到任何匹配的行.当没有匹配的记录或结果集已用完时,大多数数据库获取函数返回 null 或空数组.

When you receive this error after fetching data from the database then it means that the database didn't found any matching rows. Most database fetching functions return either null or an empty array when there are no matching records or when the result set has been exhausted.

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

To solve the problem you need to check for the truthiness of the value or for the existence of the key that you want to access.

$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>";
}

如果您想要的是结果数组中的单个值,那么您可以指定一个默认值,以防结果不存在.

If what you are after is a single value from the result array then you can specify a default in case the result is not present.

$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.

The same applies to 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;

这篇关于如何修复尝试访问类型为空值的数组偏移量错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆