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