Take the 2-minute tour ×

I'm calling the Facebook graph api via the php sdk and when I call and traverse the array through several nested foreach loops it takes far longer than it should even when I limit the # of records being called. Here's my code:

foreach ($userfriends['data'] as $friends) {
  foreach ($friends as $key => $value) {
    if($key == "id"){
      $friend_id = $value;      

    try {
      $username = $key;
      $uservar = '/'.$username.'/likes?fields=id,category&limit=20';
      $userlikes = $facebook->api($uservar);
    catch (FacebookApiException $e) {

    foreach ($userlikes['data'] as $likes) {
      foreach ($likes as $key => $value) {
        if($key == "id"){
          $like_id = $value;        
        if($key == "category"){
          $userlike_category_id = $value;       

      $sql="INSERT INTO likes (like_id, category, friend_id) 
            VALUES ('$like_id', '$userlike_category_id', '$friend_id');";
share|improve this question
please use mysqli with prepared statements (php.net/manual/en/mysqli.prepare.php), because even when data comes from a trusted source, its better to escape it anyway and keep yourself safe from SQL injection –  Ben Hughes May 5 '11 at 22:10
Thanks, I will add that. Any idea as to why this script takes more than 1 minute to run? I'm not calling or writing that much data. –  mhawk May 5 '11 at 22:22

1 Answer 1

up vote 0 down vote accepted

I would counsel doing this in two hits to avoid latency problems.

  1. set a reasonable script timeout length, fetch the details from the API and cache the results.

if all goes well ..

  1. Pick up the cache and insert into your database.
share|improve this answer
thanks, what's the best way to go about that? Could you provide some example code? I'm somewhat new working with APIs. I appreciate the help! –  mhawk May 5 '11 at 23:39

Your Answer


