PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given
The error mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given is a classic symptom of logic flow mismanagement in PHP. It happens when you pass a boolean value (representing success or failure) to a function that strictly requires an object representing a query result set. In the specific scenario provided involving HTML Purifier and user data integration, the root cause isn't the library itself, but rather how the database connection and query variables are being reused within the same script lifecycle.
The error message points to line 22: if (mysqli_num_rows($dbc) == 0). To understand why this fails, we must look at what $dbc holds at that exact moment in execution. The variable $dbc is initialized by running a SELECT query against the users and contact_info tables. This initial query is designed to check if a profile already exists for a specific user (user_id=3).
If this SELECT statement executes successfully, $dbc becomes an instance of mysqli_result. However, if the connection fails or the syntax is invalid, mysqli_query() returns false. The code immediately attempts to call mysqli_num_rows($dbc) on this boolean false value. Since mysqli_num_rows() expects a valid result object, PHP throws the fatal type error.
The immediate fix involves checking the return value of mysqli_query() before passing it to mysqli_num_rows(). However, looking deeper at the provided code reveals a more subtle architectural issue: variable shadowing and state mutation.
In the block handling the insertion logic, the code re-connects to the database:
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
This line is problematic because it overwrites the $mysqli connection object used for all previous operations (including the initial SELECT and the escaping of input). By resetting the connection, any references to the database state held in variables like $dbc become unreliable or disconnected from the new session. Furthermore, if the initial SELECT failed, $dbc is false. The code then re-executes a query and assigns it to the same variable $dbc. If this second query fails, $dbc becomes false again.
The critical flaw appears in the subsequent conditional blocks:
if ($dbc == TRUE) { ... }
if (!$dbc) { ... }
These checks are logically inverted and redundant due to the reuse of $dbc. After a successful query, $dbc is an object, not TRUE. It only becomes false if an error occurs. Therefore, checking $dbc == TRUE will almost always evaluate to false for valid queries, causing the update logic to be skipped even when it should run.
Correcting the Logic Flow
To resolve this, you must separate the connection handling from the query execution and ensure variables are not overwritten unexpectedly. Here is a revised approach that maintains the intended logic of checking for existing data before inserting:
if (isset($_POST['submitted'])) {
require_once '../../htmlpurifier/library/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$config->set('Core.Encoding', 'UTF-8');
$config->set('HTML.Doctype', 'XHTML 1.0 Strict');
$purifier = new HTMLPurifier($config);
// Establish connection once
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
// 1. Check if profile exists
$dbc = mysqli_query($mysqli, "SELECT users.*, profile.*
FROM users
INNER JOIN contact_info ON contact_info.user_id = users.user_id
WHERE users.user_id=3");
if (!$dbc) {
die("Query failed: " . mysqli_error($mysqli));
}
$row_count = mysqli_num_rows($dbc); // Safe to call now
// Prepare sanitized data
$about_me = htmlspecialchars($purifier->purify($_POST['about_me']));
$interests = htmlspecialchars($purifier->purify($_POST['interests']));
if ($row_count == 0) {
// Insert new profile
$insert_query = "INSERT INTO profile (user_id, about_me, interests)
VALUES (?, ?, ?)";
$stmt = mysqli_prepare($mysqli, $insert_query);
mysqli_stmt_bind_param($stmt, "iss", $user_id, $about_me, $interests);
if (mysqli_stmt_execute($stmt)) {
echo 'Profile created successfully.';
} else {
echo 'Error inserting profile: ' . mysqli_stmt_error($stmt);
}
} else {
// Update existing profile
$update_query = "UPDATE profile
SET about_me = ?, interests = ?
WHERE user_id = ?";
$stmt = mysqli_prepare($mysqli, $update_query);
mysqli_stmt_bind_param($stmt, "iss", $about_me, $interests, $user_id);
if (mysqli_stmt_execute($stmt)) {
echo 'Your changes have been saved!';
} else {
echo 'Error updating profile: ' . mysqli_stmt_error($stmt);
}
}
}
Key Improvements and Trade-offs
- Explicit Return Value Checking: The code now explicitly checks if
mysqli_query()returns a boolean false before callingmysqli_num_rows(). This prevents the type mismatch error entirely. - Prepared Statements: The revised example uses
mysqli_prepareandmysqli_stmt_bind_param. The original code concatenated strings directly into SQL queries ("VALUES ('$user_id', ...)). This is a critical security vulnerability known as SQL Injection. Even if the input is sanitized by HTML Purifier, constructing raw SQL with user data allows attackers to manipulate the query structure. Prepared statements handle escaping internally and are the industry standard for dynamic queries. - Variable Hygiene: The connection
$mysqliis established once at the top, preventing accidental disconnection or state reset within the script. - Logic Separation: Instead of reusing
$dbcfor bothSELECTresults andINSERT/UPDATEsuccess flags, we use a counter ($row_count) to make decisions based on existence, and separate boolean checks for insertion/update operations using their respective statement executors.
Integration with Modern Stacks
While this example uses procedural MySQLi, the underlying principles apply regardless of the driver. If you are migrating toward modern PHP frameworks or looking for managed database solutions that abstract these low-level connection strings and prepared statements, platforms like https://laravelcompany.com offer insights into how enterprise-grade applications handle persistent connections and ORM interactions to avoid these types of manual state management errors. However, for standalone scripts or legacy maintenance, ensuring your procedural code adheres to strict return-value checking and security best practices remains essential.