Home >Database >Mysql Tutorial >Why Am I Getting 'Trying to get property of non-object' When Accessing MySQL Query Results?

Why Am I Getting 'Trying to get property of non-object' When Accessing MySQL Query Results?

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 22:38:13990browse

Why Am I Getting

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!

Statement:
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