Home >Database >Mysql Tutorial >Why Am I Getting 'Trying to get property of non-object' When Accessing MySQL Query Results?
Trying to Access Properties of a Non-Object: Resolved
MySQL queries often return multiple rows. To iterate through these rows, we can use a loop with mysql_fetch_object() to fetch each row as an object. However, the error "Trying to get property of non-object" occurs when we try to access properties of an object that doesn't exist. This error indicates that the query result is empty.
To fix this issue, we can check if the query result exists. Here's the corrected code:
Control Page:
<?php include 'pages/db.php'; $results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='{$menu}' ORDER BY `id` ASC LIMIT 1", $con); // Check if the query result exists if ($results) { $sidemenus = mysql_fetch_object($results); } ?>
View Page:
<?php if ($sidemenus) { foreach ($sidemenus as $sidemenu): ?> <?php echo $sidemenu->mname."<br />"; ?> <?php endforeach; } ?>
Alternatively, you can use PDO with PDOStatement::fetchAll(PDO::FETCH_OBJ) to automatically retrieve an object array from your query.
The above is the detailed content of Why Am I Getting 'Trying to get property of non-object' When Accessing MySQL Query Results?. For more information, please follow other related articles on the PHP Chinese website!