How to Handle 'Trying to Access Array Offset on Value of Type Null' Error in PHP?

Barbara Streisand
Release: 2024-11-14 19:19:02
Original
790 people have browsed it

How to Handle

Error "Trying to Access Array Offset on Value of Type Null" in PHP

This error occurs during database fetching when the database returns no matching rows or the result set has been exhausted. Database functions return null or an empty array when no matching records exist.

To resolve the issue, check the truthiness of the value or confirm the existence of the key you intend to access. Consider the following example:

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

For a single value from the result array, you can specify a default in case the result is empty:

$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;
Copy after login

The same approach 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;
Copy after login

The above is the detailed content of How to Handle 'Trying to Access Array Offset on Value of Type Null' Error in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template