Home > Backend Development > PHP Tutorial > Why Do I Get the 'Trying to Access Array Offset on Value of Type Null' Error When Querying a Database?

Why Do I Get the 'Trying to Access Array Offset on Value of Type Null' Error When Querying a Database?

Mary-Kate Olsen
Release: 2024-11-11 16:27:03
Original
960 people have browsed it

Why Do I Get the

Fixing the "Trying to Access Array Offset on Value of Type Null" Error

When retrieving data from a database, it's essential to handle scenarios where no matching records exist. The error "Trying to access array offset on value of type null" arises when the database fails to find a matching row for a particular query.

Why Does This Error Occur?

Database fetching functions, like mysqli_fetch_array, return either a null value or an empty array if there are no matching records. This can happen when the query is incorrect, the data doesn't exist, or the result set has been exhausted.

Solution 1: Checking for Truthiness and Key Existence

To resolve this issue, you can verify the truthiness of the returned value and check if the specific key you want to access exists. Here's an 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

In this example, we first check if $m11to1 is not null and then verify if the key "lecture_day" exists and is not an empty string.

Solution 2: Default Values in PDO

If you're working with PDO, you can specify a default value for the result in case no matching row is found:

$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

This ensures that $lecture will not be null, even if no matching record is found.

The above is the detailed content of Why Do I Get the 'Trying to Access Array Offset on Value of Type Null' Error When Querying a Database?. 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