Home >Database >Mysql Tutorial >Why Am I Getting a 'Trying to Get Property of Non-Object' Error in My PHP Code?
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.
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;
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.
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!