Home >Database >Mysql Tutorial >Why Am I Getting a 'Trying to Get Property of Non-Object' Error in My PHP Code?

Why Am I Getting a 'Trying to Get Property of Non-Object' Error in My PHP Code?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 12:27:14431browse

Why Am I Getting a

Troubleshooting "Trying to Get Property of Non-Object" Errors

When encountering the error message "Trying to get property of non-object," it's essential to examine the context of its occurrence. Let's delve into a specific case to understand the cause and resolution.

Problem Statement

In a PHP script, a query retrieves data from a database, but when attempting to access specific properties of the retrieved result, the error arises. The code snippets involved are as follows:

Control Page

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

View Page

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

Cause Analysis

The root cause lies in the assumption that mysql_fetch_object() returns an array of objects, whereas in reality it retrieves only a single object. When iterating over the result in the view page, it attempts to access properties of an array element, which in this case is not an array but rather a singular object.

Resolution

To resolve the issue, a suitable modification to the script is required. One possible solution is to convert the result into an array of objects using a loop:

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

By iterating over the result using a while loop, each object can be added to the $sidemenus array, creating an array that can be accessed as expected in the view page.

The above is the detailed content of Why Am I Getting a 'Trying to Get Property of Non-Object' Error in My PHP Code?. 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