Home > Backend Development > PHP Tutorial > How to Fix the 'Trying to Get Property of Non-Object' Error in PHP?

How to Fix the 'Trying to Get Property of Non-Object' Error in PHP?

DDD
Release: 2024-11-08 15:44:02
Original
961 people have browsed it

How to Fix the

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template