Web Development

Unexpected return value from Facebook FQL.query

While working with FQL I suddenly found a bug in one of our applications. Sometime you need to display how many of your friends added this application to their facebook profile. To do that you can execute the following query via the available REST library for PHP developers.

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. Number of elements in that array is 0 and you will get an expected result. But actually the method returns a white space. Thats why count(” “) will give you “1″ and produces an unexpected result. Using the above method you will get “1″ when you have no friends.

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})");
if (is_array($Users))
$NumberOfUsers = count(trim($Users));
else
$NumberOfUsers=0;
return $NumberOfUsers;
}

About the author

Written by .

If you found this post useful you may also want to check these out:

  1. Create a Facebook Application With PHP
  2. How Many Users Online?
  3. Developing State-enabled Applications With PHP
  4. Inserting An Array Into A Database
  5. Showing MySQL Results in Pages
  6. Answers To Questions About JavaScript