stackoverflow stackoverflow - 3 months ago 12
MySQL Question

Notice: Trying to get property of non object

I am getting a Notice: Trying to get property of non-object in the line

if ($resCategory->num_rows > 0)
. May I know what is the mistake here?

<?php
function categoryParentChildTree($parent = 'L1', $spacing = '', $category_tree_array = '') {
global $MySQLi_CON;
$parent = $MySQLi_CON->real_escape_string($parent);
if (!is_array($category_tree_array))
$category_tree_array = array();
$sqlCategory = "SELECT * FROM users where enrolled_id = $parent ORDER BY enrolled_id ASC";
$resCategory=$MySQLi_CON->query($sqlCategory);
if ($resCategory->num_rows > 0) {
while($rowCategories = $resCategory->fetch_assoc()) {
$category_tree_array[] = array("id" => $rowCategories['enroller_id'], "name" => $spacing . $rowCategories['user_name']);
$category_tree_array = categoryParentChildTree($rowCategories['enroller_id'], '&nbsp;&nbsp;&nbsp;&nbsp;'.$spacing . '-&nbsp;', $category_tree_array);
}
}
return $category_tree_array;
}
?>

Answer

You need to wrap TEXT parameters in single quotes like this and its also a good idea to wrap table names and column names in backticks

You should also get into the habit of checking the status of all API calls like this

$sqlCategory = "SELECT * FROM `users` where `enrolled_id` = '$parent' 
                ORDER BY `enrolled_id` ASC";
$resCategory=$MySQLi_CON->query($sqlCategory);
if ( !$resCategory ) {
    echo $MySQLi_CON->error;
    exit;
}

To be safe from SQL Injection attacks you should also use prepared, parameterised queries as well

"SELECT * FROM `users` where `enrolled_id` = ? 
 ORDER BY `enrolled_id` ASC";

$stmt = $MySQLi_CON->prepare($sqlCategory);
if ( !$stmt ) {
    echo $MySQLi_CON->error;
    exit;
}

$MySQLi_CON->bind_param('s', $parent);
$status = $MySQLi_CON->execute();

if ( !$status ) {
    echo $MySQLi_CON->error;
    exit;
}