Home >Backend Development >PHP Tutorial >Why Am I Getting the 'Trying to get property of non-object' Error When Accessing Database Results in PHP?

Why Am I Getting the 'Trying to get property of non-object' Error When Accessing Database Results in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 04:10:02709browse

Why Am I Getting the

Error: "Trying to get property of non-object" When Accessing Database Results

When attempting to access database results in PHP, you may encounter the error "Trying to get property of non-object." This error occurs when you try to access a property of a database result object that is not available.

To resolve this issue, verify that your database query is returning the expected result and that the data type of the returned variable is correct.

Origin of the Error

Consider this sample code where the error in question might manifest:

// Retrieve a single row from the database
$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id` = '{$menu}' ORDER BY `id` ASC LIMIT 1", $con);

// Attempt to access the result as an object
$sidemenus = mysql_fetch_object($results);

// Iterate over the result and display properties
foreach ($sidemenus as $sidemenu) {
    echo $sidemenu->mname . "<br />";
}

The error can occur in the foreach loop because mysql_fetch_object() returns a single object, not an array of objects. As a result, you cannot iterate over it like an array.

Solution

To fix this issue, you can modify the code to fetch the results correctly. One option is to use mysql_fetch_array() instead of mysql_fetch_object(), which returns an array of the row's values.

Alternatively, you can use a loop to fetch all rows and store them in an array:

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

// Iterate over the sidemenus array and display properties
foreach ($sidemenus as $sidemenu) {
    echo $sidemenu->mname . "<br />";
}

Additional Considerations

Consider using a database abstraction layer such as PDO instead of the obsolete MySQL functions. PDO provides a more modern and secure way to interact with databases.

For example, to use PDO to fetch a single row as an object:

$sth = $pdo->prepare("SELECT * FROM sidemenu WHERE `menu_id` = :menu_id ORDER BY `id` ASC LIMIT 1");
$sth->execute([':menu_id' => $menu]);
$sidemenu = $sth->fetchObject();

if ($sidemenu) {
    echo $sidemenu->mname;
}

The above is the detailed content of Why Am I Getting the 'Trying to get property of non-object' Error When Accessing Database Results in PHP?. 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