2

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;
1
  • Debugging the code would give you some insight into what $result actually is. Also, don't forget your friend is_array(). Commented May 26, 2010 at 18:16

4 Answers 4

7

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

use mysql_num_rows instead of count. count returns 1 for the value FALSE

1 Comment

$numrows = mysql_num_rows($q);
1

count() returns 1 because in case of failure $check is not an array.

From the documentation:

If var is not an array or an object with implemented Countable interface, 1 will be returned

But you should anyway handle error cases directly (if the query fails your code shouldn't even get to the point where you analize its results). Also as other have correctly said, that's not how you count the number of results a query returns as that's what mysql_num_rows() is for

Comments

0

mysql_fetch_array returns false if there are no more rows. count(false) = 1.

Try using mysql_num_rows if you want to count the number of results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.