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

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

问题描述

我正在使用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也是如此.

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

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

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