This warning occurs when mysqli_num_rows() is called on a boolean (false) instead of a mysqli_result object. This typically happens when your MySQL query fails, and mysqli_query() returns false instead of a result object.
Common Causes & Solutions
1. Query Syntax Error
$result = mysqli_query($connection, "SELECT * FROM users WHERE username = 'john_doe'");
// If the query fails, $result will be false
if (mysqli_num_rows($result) > 0) { // Warning here if query failed
// ...
}
Fix: Always check if the query succeeded first:
$result = mysqli_query($connection, "SELECT * FROM users WHERE username = 'john_doe'");
if ($result === false) {
die("Query failed: " . mysqli_error($connection));
}
if (mysqli_num_rows($result) > 0) {
// Row exists
}
2. Connection Issues
If your database connection failed, queries will return false.
Fix: Verify the connection:
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
3. Table Doesn't Exist or Typo in Table Name
$result = mysqli_query($connection, "SELECT * FROM non_existent_table");
// Returns false if table doesn't exist
Fix: Check your table names.
4. Using Prepared Statements Incorrectly
$stmt = mysqli_prepare($connection, "SELECT * FROM users WHERE id = ?");
// Forgot to bind parameters or execute
$result = mysqli_stmt_get_result($stmt); // Might return false
Fix: Proper prepared statement usage:
$stmt = mysqli_prepare($connection, "SELECT * FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($result && mysqli_num_rows($result) > 0) {
// Row exists
}
Best Practice Solution
Here's a robust way to check if a row exists with proper error handling:
function rowExists($connection, $table, $column, $value) {
$table = mysqli_real_escape_string($connection, $table);
$column = mysqli_real_escape_string($connection, $column);
$query = "SELECT 1 FROM `$table` WHERE `$column` = ? LIMIT 1";
$stmt = mysqli_prepare($connection, $query);
if (!$stmt) {
die("Prepare failed: " . mysqli_error($connection));
}
mysqli_stmt_bind_param($stmt, "s", $value);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($result === false) {
die("Query failed: " . mysqli_error($connection));
}
return mysqli_num_rows($result) > 0;
}
// Usage:
if (rowExists($connection, 'users', 'email', 'user@example.com')) {
echo "User exists!";
}
This approach:
- Uses prepared statements to prevent SQL injection
- Properly escapes table/column names
- Includes comprehensive error checking
- Is efficient with
LIMIT 1