How to Handle 'Trying to access array offset on value of type null' Error in PHP Data Fetching?

Susan Sarandon
Release: 2024-11-11 19:48:03
Original
595 people have browsed it

How to Handle

Fixing "Trying to access array offset on value of type null" Error in PHP Data Fetching

When attempting to fetch data from a database using PHP, encountering the "Trying to access array offset on value of type null" error indicates that the database failed to locate any matching rows. In PHP, database fetching functions typically return either null or an empty array in such scenarios.

To resolve this issue, ensure that the data being fetched exists by verifying the query string and checking for the presence of the key you intend 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>";
}
Copy after login

Alternatively, you can specify a default value in case the result is not present:

$lecture = $m11to1["lecture_day"] ?? null;
Copy after login

These techniques apply to both mysqli and PDO. By checking for the truthiness or existence of keys, you can handle empty results gracefully and avoid the aforementioned error.

The above is the detailed content of How to Handle 'Trying to access array offset on value of type null' Error in PHP Data Fetching?. 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