Question

this function to return number of rows for unique users returns 1 as expected but why when checking against an IF statement to see whether it ===1 (also tried ==1) does it return true even if the user does not exist?

function test($user) {
global $link;
$query = "SELECT COUNT('iD') FROM eif WHERE userName = '$user'";
$result = mysqli_query($link,$query) or die(mysqli_error($link)); //or die(mysql_error());
$return_rows =  mysqli_num_rows($result);

echo $return_rows, " is the number of rows", '<br>'; //this displays "1 is the number of the rows"
return $return_rows;
}


//$user = "austin16";

if(test($user)===1){
echo "yes ",$user," does exist";
} else{ echo " no ",$user," does not exist";}

//if $user="austin316" the IF returns TRUE however if $user="austin" it also returns     TRUE but austin does not exist

?>

Many Thanks for taking a look.

Was it helpful?

Solution

Your query will always return one row, COUNT() will return the number of rows that match your WHERE clause. You can either select something that is not an aggregate function, or compare to the value that is returned. The easiest fix would be to change your COUNT('iD') to just simply ID, so your $query line will be $query = "SELECT iD FROM eif WHERE userName = '$user'";

This will make it so that your $return_rows variable returns the correct value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top