Sample FQL Queries
From Facebook Developers Wiki
This article describes some example FQL queries.
Get the uids of all friends of the $app_user who have the application installed:
| SELECT uid FROM user WHERE has_added_app = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = $app_user) |
Get the names of the groups of which u1 is a member:
| SELECT name FROM group WHERE gid IN (SELECT gid FROM group_member WHERE uid = ''u1'') |
Get uids of friends of $app_user with birthdays today (where $today is formatted like December 18):
| SELECT uid FROM user WHERE strpos(birthday, "$today") = 0 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = $app_user) |
NOTE: The above clearly will not work for three days of the month (first two only for February), such as if $today is 'July 2', anyone's birthday that begins with the string 'July 2' will result in a match (i.e. July 21, July 27, etc). To solve this, you need to set a $todaylength = strlen($today) variable to track the string's length, this will take care of the birthdays without years; to deal with birthdays with years, make another strpos check that "July 2," string, notice the comma. See below code:
| SELECT uid FROM user WHERE (strpos(birthday, "$today") = 0 AND strlen(birthday) = $todaylength OR strpos(birthday, "$today,") = 0 ) AND uid IN (SELECT uid2 FROM friend WHERE uid1 = $app_user) |
See groups' names that u1 shares with u2:
| SELECT name FROM group WHERE gid IN ( SELECT gid FROM group_member WHERE uid=''u1'' AND gid IN (SELECT gid FROM group_member WHERE uid=''u2'')) |
Get pids in range (1,42) from $user_id's albums, sorted by created date:
| SELECT pid FROM photo WHERE aid IN ( SELECT aid FROM album WHERE owner=''$user_id'' ) ORDER BY created DESC LIMIT 1,42 |
In PHP, it would look like this (make sure you include facebook.php and lib):
| $query = "YOUR QUERY HERE"; //(see above examples) $array = $facebook->api_client->fql_query($query); |
The returned array is multidimensional, so an easy way to get at the data without the foreach loop (assuming you've only pulled one row, that is, using "WHERE uid=$user") would be:
| $attribute = $array[0]['attribute']; |
If there are no rows returned (that is, you look for photos of people together but no photos of them exist), the Facebook PHP client returns an empty string. You can check to see if there are any results like this:
| if ($result != NULL) |
