JRsz JRsz - 4 months ago 13x
SQL Question

MySQL - select count returns true

I am trying to determine whether an email is aready in my database or not. For this purpose I write this piece of code:

$query_checkmail = "SELECT COUNT(*) FROM user WHERE email = ?;";
if($stmt = mysqli_prepare($connection, $query_checkmail))
mysqli_stmt_bind_param($stmt, "s", $_POST["email"]);
$result = mysqli_stmt_execute($stmt);

echo "<pre>";
var_dump($result, mysqli_fetch_all($result));
echo "</pre>";

Since I expect the query to return 0 because the email should not be in the database, the output is this (from


I do not understand why I do not get a mysqli result object with the value 0 but instead the boolean value true which always triggers a PHP Warning in the logs if I want to check it.

I had a normal
SELECT id FROM user WHERE email = ?;";
before and got the same result. I thought with COUNT I could prevent this but my attempt has obviously failed.

I also found this Stackoverflow Link but unfortunatly it did not help my to solve my problem of getting to know whether the value already exists or not.

Any help is highly appreciated. If this information is not enough I will provide the missing bits immediatly.


The count itself doesn't return a boolean true or false, you're checking against a variable assigned from mysqli_stmt_execute(), which returns a boolean. This has nothing to do with the results of the query. If you'll read the documentation on this function, specifically the return values of mysqli_stmt_execute(), you'll see that they are either true or false, so there is no surprise that a var_dump() of that would return a boolean.

If you want the actual count, you have to use mysqli_stmt_bind_result() and mysqli_stmt_fetch() to get the results of the count. This would produce the correct results. The manuals of this would show examples of that if you are unsure how to use these functions.

As for the NULL, it's because you're passing a boolean into the mysqli_fetch_all() function, which expects a mysqli_result, while you're giving it a boolean from the above-mentioned reasons.