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);
// View page foreach ($sidemenus as $sidemenu) { echo $sidemenu->mname."<br />"; }
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; }
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!