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