How to fix Trying to access array offset on value of type null error

When you receive this error after fetching data from the database then it means that the database didn’t found any matching rows. Most database fetching functions return either null or an empty array when there are no matching records or when the result set has been exhausted.

To solve the problem you need to check for the truthiness of the value or for the existence of the key that you want 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>";
}

If what you are after is a single value from the result array then you can specify a default in case the result is not present.

$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 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;

Leave a Comment