Home > Backend Development > PHP Tutorial > Why Am I Getting the 'Trying to Get Property of Non-Object' Error in PHP?

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

DDD
Release: 2024-11-10 12:46:02
Original
1036 people have browsed it

Why Am I Getting the

Trying to Get Property of Non-Object in PHP: A Detailed Explanation

In PHP, encountering the "Trying to get property of non-object" error message can be perplexing. To delve into the cause and resolution of this error, let's analyze the provided code snippets:

// Control page
$results = mysql_query(...);
$sidemenus = mysql_fetch_object($results);
Copy after login
// View page
foreach ($sidemenus as $sidemenu) {
    echo $sidemenu->mname."<br />";
}
Copy after login

The issue arises because mysql_fetch_object() returns a single object representing the first row of the result set, whereas the loop in the View page treats $sidemenus as an array and attempts to access its elements as objects.

// Fix
$results = mysql_query(...);

$sidemenus = array();
while ($sidemenu = mysql_fetch_object($results)) {
    $sidemenus[] = $sidemenu;
}
Copy after login

This revised code initializes $sidemenus as an array and iterates over the result set, adding each object to the array. Subsequently, the View page can safely loop over $sidemenus as an array of objects.

Alternatively, for more efficient database handling, consider switching to PDO (PHP Data Objects). PDOStatement::fetchAll(PDO::FETCH_OBJ) provides a similar functionality, but with improved performance and security.

The above is the detailed content of Why Am I Getting 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