How to fix "Trying to get property 'num_rows' of non-object" error?
25
I'm getting this error: "Trying to get property 'num_rows' of non-object"
Here's my code:
// 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
}
What's causing this error and how can I fix it?
1 Answer
32
This error occurs because $result is not a valid MySQLi result object. The issue is in your code flow. Here's how to fix it:
The Problem
You're calling get_result() on a prepared statement without executing it first.
Correct Approach
<?php
// Query
$query = "SELECT * FROM table_name WHERE column = ?";
// Preparation
$stmt = $conn->prepare($query);
// Bind parameters
$stmt->bind_param("s", $value);
// Execute the statement
$stmt->execute();
// Get result
$result = $stmt->get_result();
// Check number of rows
if ($result->num_rows > 0) {
$data = $result->fetch_assoc();
// Your PHP code here
}
// Close statement
$stmt->close();
?>
Alternative Approach (Direct Query)
<?php
$query = "SELECT * FROM table_name WHERE column = 'value'";
$result = mysqli_query($conn, $query);
if ($result && $result->num_rows > 0) {
$data = $result->fetch_assoc();
// Your PHP code here
}
?>
Key Points
- Always execute prepared statements before getting results
- Check if the query was successful before accessing properties
- Use proper error handling to catch database errors
- Close statements and connections when done