Why this error "Trying to get property 'num_rows' of non-object"

#26
304
1 Answer
Question Image

I am facing this error "trying to get property 'num_rows' of non-object".

My code is:

// Query 
$query = "SELECT * FROM table_name WHERE column = 'value'";
 
// Preparation
$sql = $conn->prepare($query);
 
// Get result 
$result = $sql->get_result();
 
// Check number of rows
if ($result->num_rows > 0) {
$result = $result->fetch_assoc();
        // my php code here
}
 
Please tell me the solution!
 

Related to:
phpmysqlipropertynum_rowsnon-object
0
Answer
Answer 1 of 1
# 34

Trying to get property 'num_rows' of non-object error

 

Mistake!

You are trying to use the property 'num_rows' while $result is not an object here

 

Solutions:

1. Query execution:

Execute query before checking row count

$sql->execute();

 

Your code can be like:

// Query 
$query = "SELECT * FROM table_name WHERE column = 'value'";

// Preparation
$sql = $conn->prepare($query);

//Execution
$sql->execute();

// Get result 
$result = $sql->get_result();

// Check number of rows
if ($result->num_rows > 0) {
       $result = $result->fetch_assoc();
        // your php code here
  }

 

2. Recommended query:

// Query 
$query = "SELECT * FROM table_name WHERE column = 'value'";

$result = mysqli_query($conn, $query);

// Check number of rows
if ($result->num_rows > 0) {
$result = $result->fetch_assoc();
print_r($result);
// your php code here
}
0
0
0
Related Articles

If you still have a question about this, submit it in our Q&A community - Ask Question