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?
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>"; }
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;
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!