While working with FQL I suddenly found a bug in one of our applications. The method which we used to count number of friends of a specific user who has added that application was returning 1 when there is no friend actually installed it। Using the following FQL you can easily find that. (FQL doesn’t support “count” – so you cant use it)
SELECT uid FROM user WHERE has_added_app = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = {$userid})
The PHP code may look like the following one
function getTotalFriends($userid)
{
global $facebook, $mysql;
$Users = $facebook->api_client->fql_query("SELECT uid FROM user WHERE has_added_app = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = {$userid})");
$NumberOfUsers = count(trim($Users));
return $NumberOfUsers;
}
So what would you expect when there is no friend who has added this application? Definitely the FQL query should return an empty array. So that counting elements of that array tells you that you have “0” friends. But actually it returns a white space. What’s the difference between an empty array and a white space? l
count(array()) returns 0
count (” “) returns 1
So even when you dont have any friends, your method actually returns you “1”. The return result is not expected. What does your common sense says? Either the method should return false or an empty array. Not a white space.
Here’s the correction
function getTotalFriends($userid)
{
global $facebook, $mysql;
$Users = $facebook->api_client->fql_query("SELECT uid FROM user WHERE has_added_app = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = {$userid})");
$NumberOfUsers = is_array($Users)?count($Users):0;
return $NumberOfUsers;
}