Solved - How to fix Trying to access array offset on value of type null error
Get the solution ↓↓↓I am creating a time table view using PHP, in which I am getting the lecture data according to the day and time.
Here is the code which I have did
$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["lecture_day"] == !'') {
echo "<td>".$m11to1["lecture_name"]."</td>";
} else {
echo "<td> no class</td>";
}
But I am getting below error for the above code:
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\nexgschool\admin\notify\add_time_table.php on line 45
Answer
Solution:
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 eithernull
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;
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: object of class stdclass could not be converted to string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.