Tiago Tiago - 1 year ago 87
MySQL Question

Mysqli - Equal and Different Expression

I'm having some problems with my query that is always returning false, but it should return true if not exists.
The problem is since the expression doesn't exists, it turns false false.

function isRegistered($mysqli, $username, $sitename, $status){
if($stmt = $mysqli->prepare("SELECT COUNT(*) FROM table1 WHERE username= ? AND sitename = ? AND status != ?")){
$stmt->bind_param("sss", $username, $sitename, $status);
if($stmt->num_rows == 0){
return true;
return false;


I'm after that seeking if the function is true or false. If it's false, it trhows an error, if it's true, it follows for the next step. The problem is that always coming false (even if thats not true).

Basically the user only can register once in a specific area. So the first time it should be allowed, and the second time it doesnt. Could someone check what's going wrong with my query?

Answer Source

The number of rows for an aggregation query is always 1. If nothing matches the WHERE clause, then one row will be returned with the value of "1".

You can fix this either by changing the SELECT COUNT(*) to something non-aggregated, such as SELECT 1 or SELECT username. Or, you can read the value of COUNT(*) back from the query and use that.

I'll let you choose how to proceed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download