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>"; }
Alternatively, you can specify a default value in case the result is not present:
$lecture = $m11to1["lecture_day"] ?? null;
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!