Link to home
Start Free TrialLog in
Avatar of dkilby
dkilbyFlag for Canada

asked on

PHP return true / false depending on number of rows.

I am trying to check if a username is already used in tblUsers, but for some reason it returns true, even though it should be false as the number of rows should come back as zero.

    $usernamequery = "SELECT COUNT(`userID`) FROM `tblUsers` WHERE `username` = '$username'";
    $query = mysqli_query($con, $usernamequery);
    $queryarray = mysqli_fetch_array($query, MYSQLI_BOTH);
    $queryarrayres = mysqli_num_rows($query);
     print_r(mysqli_num_rows($query));
    return ($queryarrayres > 0)?true:false;
ASKER CERTIFIED SOLUTION
Avatar of steveo2
steveo2
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You don't need to remove COUNT() you can just do this
1. Give the COUNT() an alias - not necessary but easier if you do
2. you are calling mysqli_fetch_array - which gets an associative and 0 indexed array - this will help if you don't alias your COUNT() but it does have some side effects you should be aware of - especially when you iterate over the returned array - field values will be duplicated. I prefer fetch_object
3. Return the value of the count as your true / false value

$usernamequery = "SELECT COUNT(`userID`) AS TotalUsers FROM `tblUsers` WHERE `username` = '$username'";
$query = mysqli_query($con, $usernamequery);
$queryarray = mysqli_fetch_object($query);
// TotalUsers will be 0 if there are none - which is a falsy value - 
// everything else will be truthy so you can just return the value
return $queryarray->TotalUsers; 

Open in new window


By removing the COUNT() you are potentially compromising efficiency as your query could return more than one row (unlikely in this case - but in general something to think about) - you are then doing a fetch_array (which you don't use) and a num_rows() - so lots of spinning the CPU's wheels unnecessarily.