"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why am I getting the "Trying to get property of non-object" error when accessing database results?

Why am I getting the "Trying to get property of non-object" error when accessing database results?

Published on 2024-11-18
Browse:155

Why am I getting the

Trying to Access Property of Non-Object

While attempting to retrieve data from a database, you encounter the error "Trying to get property of non-object." This error occurs when you try to access a property of a null or non-existent object.

In your specific scenario, you have the following code on your Control page:

$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);
$sidemenus = mysql_fetch_object($results);

And on your View page:

foreach ($sidemenus as $sidemenu): 
  echo $sidemenu->mname."<br />";
endforeach; 

The error originates because mysql_fetch_object() returns an object, not an array of objects. Therefore, in the View page, you attempt to iterate over a non-iterable object, which leads to the error.

Solution:

To resolve the issue, you should either:

  • Convert the result to an array:
$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);

$sidemenus = array();
while ($sidemenu = mysql_fetch_object($results)) {
    $sidemenus[] = $sidemenu;
}

This will convert the results into an array of objects, which you can then iterate over in your View page.

  • Use PDO:

PDO provides a more modern and efficient way to interact with databases. PDOStatement::fetchAll(PDO::FETCH_OBJ) returns an array of objects, similar to the functionality you were expecting from mysql_fetch_object().

$stmt = $con->prepare("SELECT * FROM sidemenu WHERE `menu_id` = :menu_id ORDER BY `id` ASC LIMIT 1");
$stmt->bindParam(':menu_id', $menu);
$stmt->execute();

$sidemenus = $stmt->fetchAll(PDO::FETCH_OBJ);

By utilizing either of these solutions, you can retrieve the data from the database and avoid the error "Trying to get property of non-object."

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3