Trying to get property of non-object in
You are encountering the error Notice: Trying to get property of non-object because your PHP code attempts to access properties on a variable that is either null or an empty array. In this specific scenario, the mismatch occurs between how data is retrieved from the database and how it is iterated over in the view logic.
Let's break down exactly where the failure happens. On your Control page, you execute a query using the legacy mysql_query function:
include 'pages/db.php';
$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);
$sidemenus = mysql_fetch_object($results);
Here, $sidemenus is expected to be a single object representing one row from the sidemenu table. The mysql_fetch_object() function returns an object if a row exists, or null if the query returned no rows. However, there is a critical flaw in your SQL logic combined with the data structure expectation.
Your SELECT * ... LIMIT 1 ensures you get at most one row. If that single row exists, $sidemenus becomes an object with properties like mname. This part seems correct assuming the database connection and query syntax are valid. The real issue arises when this data is passed to your View Page.
On the View Page, you have written:
foreach ($sidemenus as $sidemenu):
echo $sidemenu->mname."<br />";
endforeach;
This foreach loop iterates over $sidemenus. If $sidemenus is an object (which it should be based on the Control page), iterating over a single object in PHP does not yield its properties by default. It yields nothing, or depending on the PHP version and context, it might treat the object as an array of its own class name if magic methods aren't set up specifically for iteration. More importantly, if the query on the Control page returned zero rows, $sidemenus is null. Attempting to iterate over null or accessing properties inside a loop that never runs due to the variable state can lead to confusing errors depending on exactly how the template engine (like Blade) or direct echo handles the variable.
However, the specific error message "Trying to get property of non-object" usually implies that $sidemenus is either null or an array when you expect it to be an object, or conversely, that inside the loop, $sidemenu becomes a string or null.
There are two primary causes here:
- The Query Returned No Rows: If there is no record matching the specific
menu_id,$resultsfrommysql_queryreturnsfalse. Consequently,mysql_fetch_object(false)returnsnull. When thisnullvalue is passed to the View Page and you try to iterate it or access$sidemenus->mname, PHP throws the notice because there is no object to inspect. - Legacy API Incompatibility: You are using the deprecated
mysql_*functions. These functions were removed in PHP 7.0. If your environment has upgraded PHP, these functions will throw fatal errors before you even reach this logic. Even if running on older PHP, the lack of error checking makes debugging difficult.
To fix this robustly, you must first validate that the data exists before attempting to iterate or access properties. Here is the corrected logic for the Control page:
include 'pages/db.php';
// Use prepared statements and a modern driver like mysqli or PDO if possible.
// For now, fixing the immediate logic with mysqli:
$stmt = mysqli_query($con, "SELECT * FROM sidemenu WHERE `menu_id`=?", [$menu]);
if ($stmt && $row = mysqli_fetch_object($stmt)) {
// Only proceed if a row was actually found
$sidemenus = $row;
} else {
// Handle the case where no menu exists for this ID
$sidemenus = null;
}
On the View Page, you need to handle the possibility that $sidemenus is null:
if (is_object($sidemenus)) {
echo $sidemenus->mname . "<br />";
} else {
// Optional: Display a default message or empty space
echo "No menu item found.";
}
If your intention was to iterate over multiple results, you should remove the LIMIT 1 from the query and change the fetch method to mysql_fetch_array() or use a loop that checks for false. However, given the WHERE ... LIMIT 1 clause, it is clear you expect a single record. In that case, the foreach loop is actually unnecessary and dangerous; you should access the property directly after validation.
The most significant long-term trade-off here is the use of the mysql_* extension. Relying on it limits you to PHP versions prior to 7 and exposes your application to known security vulnerabilities. Migrating to PDO or mysqli with prepared statements is not just a recommendation; it is a requirement for modern PHP development. This migration allows you to handle errors more gracefully, use named parameters for SQL queries, and ensures compatibility with current web server configurations.
For projects requiring rapid development without deep database customization, frameworks like Laravel provide built-in ORM capabilities that abstract these raw query issues entirely. If your goal is to build a scalable application, consider evaluating modern PHP stacks or resources available at https://laravelcompany.com which often highlight the benefits of moving away from legacy MySQL extensions toward more secure and maintainable architecture patterns.
