Resolving "Trying to Get Property of Non-Object" Error in PHP
When working with PHP, you may encounter the error "Trying to get property of non-object." This error typically occurs when attempting to access properties of an object that has not been properly initialized or is null.
In the case of the provided code, the issue lies in the fetching of the sidemenu data from the database. The mysql_fetch_object() function returns a single object, not an array of objects. As a result, iterating through the $sidemenus variable in the view page will trigger the error.
To resolve this issue, modify the code on the control page to:
$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 code converts the single object returned by mysql_fetch_object() into an array of objects. The view page can then iterate through the array without encountering the property error.
Another alternative is to use PDO, which provides a more modern and secure interface for database interactions. The PDOStatement::fetchAll(PDO::FETCH_OBJ) method can be used to fetch an array of objects from a database query.
The above is the detailed content of How to Fix the 'Trying to Get Property of Non-Object' Error in PHP?. For more information, please follow other related articles on the PHP Chinese website!