Using the Facebook PHP-SDK to run FQL

As of Facebook’s migration to the new Graph API and its OAuth 2.0 protocols, I can say that their Developer documentation has become a confusing, misleading and generally unstrung pile of semi-deprecated articles, and I’m being optimistic in doing so. Problem is lots of old articles are still in there pointing to old practices and recommendations and most of these do not come with disclaimers pointing to new recommendations, and in some extremes old soon-to-be-deprecated methods do not even have equivalents in the new APIs.

The new SDKs have not, as you can say, fallen far from the tree. While they are really great new and shiny, documentation on how to use them is still vague, missing or spread out in the internet in blogs like these, in posts from us users trying to share the information with other soon-to-be-suffering developers.

So this is an example of this, i have been using these new resources and the new PHP-SDK and have ran into various walls, so I decided to start putting some of this on my blog, for 2 reasons: to spread the word, and to have notes for myself when I come back to this.

How can I run FQL queries using the new SDK?

FQL is Facebook’s SQL alernative, allowing you to query information as you would from a huge database, this documentation is thankfully still up to date and you can see a list of “tables” you can query from, and the rest of the little tweaks you will pick up on a trial and error basis.

The old Facebook library, based on their REST API had a fairly easily and accessible method to run FQL

$facebook->api_client->fql_query("SELECT uid, pic, pic_square, name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = 111111111)");

However this (and many other methods) is no longer available in the new PHP SDK so it took me a while to figure out how to get a FQL call into the library, since the only method available in this new library was api() a polymorphic and non-documented method. I finally was able to find the answer somewhere on a similar blog that ran into the same issue. This is how its done:

<?php
	//Get Facebook SDK Object
	$config = array(
	  'appId'  => APP_ID,
	  'secret' => API_SECRET,
	  'cookie' => true,
	);

	$facebook = new Facebook($config);

	//Create Query
	$params = array(
	    'method' => 'fql.query',
	    'query' => "SELECT uid, pic, pic_square, name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = 111111111)",
	);

	//Run Query
	$result = $facebook->api($params);
?>

So once you do figure out that you can pass in the “method” parameter to define a API method to be called and then figure out that the query should be in a “query” parameter, you are set. Needless to say this might take a little longer to figure out then you would expect.

So this piece of code actually looks pretty horrid from my point of view, I don’t like having to create the array all the time to be passed to the function, so I decided to instead of using facebook’s SDK straight as is, I was going to extend it and push in some helper methods, namely a FQL helper method, this is what it looks like:

<?php

namespace App\Facebook;

include_once \ROOT_PATH . 'library/vendor/facebook/facebook.php';

class Client extends \Facebook
{
    private $config;
    private $reqPerms;

    /**
     * Runs a FQL query agains the API
     *
     * @param string $query
     * @return array
     */
    public function fql($query)
    {
        $params = array(
            'method' => 'fql.query',
            'query' =>$query,
        );

        return $this->api($params);
    }

}
$config = array(/* insert config here */);

//Using client
$fb = new App\Facebook\Client($config);

$query = "SELECT uid, pic, pic_square, name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = 111111111)";
$result = $fb->fql($query);

?>

So this makes it now nice and clean to use FQL as well as having the upside that the class is now nicely packed inside my namespace and as an added bonus, this class is now much easier to mock for unit testing, since i have a direct method to test for and not have to filter out params sent to the method.

I did go one step further with this and submitted this change to Facebook’s SDK on github as a pull request. It has not yet been replied to but i hope that soon it will make it into the actual code and more people will be able to benefit from it.

Hope you enjoy this and it gives you ideas on how to improve your usage of the Facebook PHP SDK and i’ll come back with more in the future.

This post is also available in: Portuguese (Brazil)

4 thoughts on “Using the Facebook PHP-SDK to run FQL

  1. Another bonus is that now you set up a boundary in your application. When fb-sdk get updates, you will decide the better way to expose the new features.

    It's always important to set boundaries between your code and thirdy-party code, your tests thanks.

  2. Hello Raf,

    $facebook->api_client->fql_query(); will be deprecated, is this new method will work ? it is using Graph API ?

  3. Rafael,

    This article helped me a lot to create my application. Do you know which fields have the user table?

    thank you very much

  4. If you happen to be using the Lithium framework for PHP (5.3+) you can check out: https://github.com/tmaiaroto/li3_facebook — This library allows the use of Facebook very easily within your applications and even if you aren't using Lithium you can very likely make things work because it's namespaced and all. Then it's as easy as calling FacebookProxy::api($params); and you're done. Of course if you wanted to add in another method that let's you get even shorter, then that's fine too…But if you are using PHP 5.3+ I figured this was a library worth mentioning. I did start the library, but other contributors helped and added the FacebookProxy class which is just awesome. Feel free to fork!

  5. I saw your blog’s link put up by a friend on Facebook. Thank you for putting useful information on the net. It’s hard to come by these things nowadays.

  6. I have no udea what any of this means but having gone to SMC with Raf I’m proud to see he at least looks like he knows what he’s talking about ;)

  7. Andddddd…. got it.

    $result = $facebook->api( array('method' => 'fql.multiquery','queries' => '{"friendlist":"SELECT uid, flid FROM friendlist_member WHERE flid IN '
    .'(SELECT flid FROM friendlist WHERE owner=me())"'
    .',"fll":"SELECT flid, owner, name FROM friendlist WHERE owner=me()"}'
    ) );

  8. Thanks for the post but i am having this query
    SELECT uid FROM page_fan WHERE page_id =xxx and uid=xxx
    and i tried your code it does not return anything

  9. Hi!

    I'm trying FQL, but it doesn't work fine for me…

    I was trying this query:

    $ret = $f->api(array('method' => 'fql.query', 'query' => 'select eid, uid, rsvp_status from event_member where uid = '.$user_id.';'));
    //user_id is ok

    but when I do print_r($ret); it returns an empty array…

    If I try it into FB debug tool it works…

    What can I do?

    Thanks!

  10. How to run my query "SELECT message FROM status WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) " in PHP ?
    I use sign "+" so, it become :
    // run fql query
    $fql_query_url = 'https://graph.facebook.com/&#039;
    . 'fql?q=SELECT+message+FROM+status+WHERE+uid=me()'
    . '&access_token=' . $access_token;
    $fql_query_result = file_get_contents($fql_query_url);
    $fql_query_obj = json_decode($fql_query_result, true);

    // display results of fql query
    echo '<pre>';
    print_r("query results:");
    print_r($fql_query_obj);
    echo '</pre>';

    But it doent work, help me please :(

Comments are closed.