Im trying to get the amount of elements in an array using the count() function, the result is a bit puzzling to me, considere the following example.
Assume that the user ID provided is wrong, and therefore had no matches, wouldnt then the result of the count function be 0? yet it is 1. can you explain to me why?
thanks
$q = mysql_query("select password from users where user_name = '" . $userID . "'");
$check = mysql_fetch_array($q);
$result = count($check);
echo "RESULT:" . $result;
That's the wrong way to count rows in a result set. First of all, from the documentation on mysql_fetch_array()
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
Ergo, if we do this
echo count( false );
We can see the output is 1. Why? Because the count() documentation tells us that as well
If var is not an array or an object with implemented Countable interface, 1 will be returned.
To do a proper count, use mysql_num_rows()
$q = mysql_query("select password from users where user_name = '" . $userID . "'");
$result = mysql_num_rows( $q );
if ( 0 == $result )
{
// no rows in result
}
use mysql_num_rows instead of count. count returns 1 for the value FALSE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With