title: Facebook API - Store friends in a database
body: <p>I'm a beginner with the Facebook APIs, so I thought I'd teach myself with a few pet projects. I'm currently trying to retrieve the user's friend list, check it against a database and add if it's not in. My code so far is:</p>
  
  <pre><code>&lt;?php
  
  $database = new mysqli('host', 'username', 'password', 'db');
  
  if ($users = $database-&gt;query('SELECT id FROM `friends`')) {
      while ($row = $users-&gt;fetch_assoc()) {
          $my_friend[] = $row['id'];
      }
  }
  require('src/facebook.php');
  $facebook = new Facebook(array(
              'appId' =&gt; 'id',
              'secret' =&gt; 'secret',
              'cookie' =&gt; true,
          ));
  // $session is only != null, when you have the session-cookie, that is set by facebook,      after the user logs in
  $session = $facebook-&gt;getSession();
  // you dont get a list of friends, but a list, which contains other friendlists
  $friendsLists = $facebook-&gt;api('/me/friends');
  
  // Save all Friends and FriendConnections
  foreach ($friendsLists as $friends) {
      foreach ($friends as $friend) {
          // do something with the friend, but you only have id and name
          $id = $friend['id'];
          $name = $friend['name'];
          echo $name . " (" . $id . ") &lt;br&gt;";
          if (!in_array($id, $my_friends)) {
              $query = "INSERT into friends (id,name) VALUES ($id, $name)";
              mysql_query($query);
          }
      }
  }
  </code></pre>
  
  <p>And before anyone says it, I have replaced the app id and secret so it's not that</p>