Home >Backend Development >PHP Tutorial >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?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 01:13:03404browse

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."

The above is the detailed content of Why am I getting the 'Trying to get property of non-object' error when accessing database results?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn