dkilby
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($q uery));
return ($queryarrayres > 0)?true:false;
$usernamequery = "SELECT COUNT(`userID`) FROM `tblUsers` WHERE `username` = '$username'";
$query = mysqli_query($con, $usernamequery);
$queryarray = mysqli_fetch_array($query,
$queryarrayres = mysqli_num_rows($query);
print_r(mysqli_num_rows($q
return ($queryarrayres > 0)?true:false;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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.