How to fix Trying to access array offset on value of type null error

↘锁芯ラ 提交于 2021-02-16 15:24:05

问题


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

Here is the code which I have did

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

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


回答1:


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;

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;


来源:https://stackoverflow.com/questions/65841575/how-to-fix-trying-to-access-array-offset-on-value-of-type-null-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!