Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP using count() with array

Tags:

php

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;
like image 666
seb Avatar asked Feb 18 '26 22:02

seb


2 Answers

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
}
like image 169
Peter Bailey Avatar answered Feb 21 '26 12:02

Peter Bailey


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

like image 34
Galen Avatar answered Feb 21 '26 12:02

Galen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!