Sometimes you may need to collect facebook user’s basic data for your website or application. Then you’ve to call graph api or legacy api or fql query to collect some specific data. This is a basic requirements for most of the fbconnect base website or facebook application.
For this reason, here I’m sharing the code, how could I collect those basic data and store them in database.
Before proceeding check the demo.
If you’re automatically logged in the site, then first logout and relogin and approve all the permissions. Now I’m showing the database table schema first

MySql code of this schema is:
CREATE TABLE IF NOT EXISTS `demographic` ( `uid` BIGINT UNSIGNED NOT NULL , `first_name` VARCHAR(50) NULL , `last_name` VARCHAR(50) NULL , `email` VARCHAR(200) NULL , `link` VARCHAR(255) NULL , `affiliations` VARCHAR(255) NULL , `birthday` VARCHAR(50) NULL , `current_location` VARCHAR(200) NULL , `education_history` VARCHAR(500) NULL , `work` MEDIUMTEXT NULL , `hometown_location` VARCHAR(400) NULL , `interests` VARCHAR(200) NULL , `locale` VARCHAR(50) NULL , `movies` VARCHAR(500) NULL , `music` VARCHAR(500) NULL , `political` VARCHAR(200) NULL , `relationship_status` VARCHAR(100) NULL , `sex` VARCHAR(10) NULL , `tv` VARCHAR(200) NULL , `status` TINYINT NULL , `created` DATETIME NULL , `updated` DATETIME NULL , PRIMARY KEY (`uid`) ) ENGINE = InnoDB
This code collects data from facebook
if ($fbme){
//collect some data using legacy api
$param = array(
'method' => 'users.getinfo',
'uids' => $fbme['id'],
'fields' => 'birthday_date, interests, locale, political, relationship_status, affiliations',
'callback' => ''
);
try{
$info = $facebook->api($param);
}
catch(Exception $o){
error_log("Legacy Api Calling Error!");
}
//using graph api
//array data
$workInfo = getWorkInfoAsString($fbme);
$education = getEducationAsString($fbme);
$moviesArr = $facebook->api("/me/movies");
$musicArr = $facebook->api("/me/music");
$televisionArr = $facebook->api("/me/television");
//format some api data
$movies = getArrayDataAsString($moviesArr['data']);
$music = getArrayDataAsString($musicArr['data']);
$television = getArrayDataAsString($televisionArr['data']);
//data from legacy api
$networks = '';
if (!empty($info[0]['affiliations'])){
$flag = true;
foreach ($info[0]['affiliations'] as $item){
if (!$flag) $networks.= ' # ';
$networks .= $item['name'];
$flag = false;
}
}
$now = date("Y-m-d G:i:s");
$insData = array(
'uid' => $fbme['id'],
'first_name' => $fbme['first_name'],
'last_name' => $fbme['last_name'],
'email' => isset($fbme['email']) ? $fbme['email'] : '',
'link' => $fbme['link'],
'affiliations' => $networks,
'birthday' => $info[0]['birthday_date'],
'current_location' => isset($fbme['location']['name']) ? $fbme['location']['name'] : '',
'education_history' => $education,
'work' => $workInfo,
'hometown_location' => isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '',
'interests' => $info[0]['interests'],
'locale' => $info[0]['locale'],
'movies' => $movies,
'music' => $music,
'political' => $info[0]['political'],
'relationship_status' => $info[0]['relationship_status'],
'sex' => isset($fbme['gender']) ? $fbme['gender'] : '',
'tv' => $television,
'status' => '0',
'created' => $now,
'updated' => $now,
);
//$this->db->insert('demographic', $insData);
}
function getWorkInfoAsString($fbme, $delim = '#', $partDelim = ' | '){
$info = "";
$flag = false;
if (empty($fbme['work'])) return '';
foreach($fbme['work'] as $item){
if ($flag)
$info .= $partDelim;
$flag = true;
$info .= (isset($item['employer']['name']) ? $item['employer']['name'] : '' ). $delim .
(isset($item['location']['name']) ? $item['location']['name'] : '' ). $delim .
(isset($item['position']) ? $item['position']['name'] : '' ). $delim .
(isset($item['start_date']) ? $item['start_date'] : '' ). $delim .
(isset($item['end_date']) ? $item['end_date'] : '' );
}
return $info;
}
function getEducationAsString($fbme, $delim = '#', $partDelim = ' | '){
$info = "";
$flag = false;
if (empty($fbme['education'])) return '';
foreach($fbme['education'] as $item){
if ($flag)
$info .= $partDelim;
$flag = true;
$info .= (isset($item['school']['name']) ? $item['school']['name'] : '' ). $delim .
(isset($item['year']['name']) ? $item['year']['name'] : '');
}
return $info;
}
function getArrayDataAsString($data, $delim = '#', $partDelim = ' | '){
$info = "";
$flag = false;
foreach($data as $item){
if ($flag)
$info .= $partDelim;
$flag = true;
$info .= $item['name'];
}
return $info;
}
Look $insData contains all the values. So you just need to insert $insData in your database table. In this example I used mainly graph api, and for some small information I call legacy api. Regarding data storing format, if I found any data as array like education_history then I store that data like below format
[education_history] => International Islamic University Chittagong#2008 | Govt. Shah Sultan College, Bogra#2003
first # for part of a single data like (education institute and year), and finally | that separates array item. If your profile has well filled data then by visiting this demo you will see the data example.
So if you store education_history and next time you need to break them as array then you could write code like
$arrEdu = explode('|', $education_history); // break string to array items
$education = array();
$i = 0;
foreach($arrEdu as $item){
$brk = explode('#', $item);
$education[$i]['institute'] = $brk[0];
$education[$i]['year'] = $brk[1];
++$i;
}
echo '<pre>';
print_r($education);
echo '</pre>';
This will output
Array
(
[0] => Array
(
[institute] => International Islamic University Chittagong
[year] => 2008
)
[1] => Array
(
[institute] => Govt. Shah Sultan College, Bogra
[year] => 2003
)
)
If you read the code you’ll see its very easy to understand.
Full Source Code
<?php
include_once "fbmain.php";
$config['baseurl'] = "http://thinkdiff.net/demo/newfbconnect1/demographicdata/index.php";
//if user is logged in and session is valid.
if ($fbme){
//collect some data using legacy api
$param = array(
'method' => 'users.getinfo',
'uids' => $fbme['id'],
'fields' => 'birthday_date, interests, locale, political, relationship_status, affiliations',
'callback' => ''
);
try{
$info = $facebook->api($param);
}
catch(Exception $o){
error_log("Legacy Api Calling Error!");
}
//using graph api
//array data
$workInfo = getWorkInfoAsString($fbme);
$education = getEducationAsString($fbme);
$moviesArr = $facebook->api("/me/movies");
$musicArr = $facebook->api("/me/music");
$televisionArr = $facebook->api("/me/television");
//format some api data
$movies = getArrayDataAsString($moviesArr['data']);
$music = getArrayDataAsString($musicArr['data']);
$television = getArrayDataAsString($televisionArr['data']);
//data from legacy api
$networks = '';
if (!empty($info[0]['affiliations'])){
$flag = true;
foreach ($info[0]['affiliations'] as $item){
if (!$flag) $networks.= ' # ';
$networks .= $item['name'];
$flag = false;
}
}
$now = date("Y-m-d G:i:s");
$insData = array(
'uid' => $fbme['id'],
'first_name' => $fbme['first_name'],
'last_name' => $fbme['last_name'],
'email' => isset($fbme['email']) ? $fbme['email'] : '',
'link' => $fbme['link'],
'affiliations' => $networks,
'birthday' => $info[0]['birthday_date'],
'current_location' => isset($fbme['location']['name']) ? $fbme['location']['name'] : '',
'education_history' => $education,
'work' => $workInfo,
'hometown_location' => isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '',
'interests' => $info[0]['interests'],
'locale' => $info[0]['locale'],
'movies' => $movies,
'music' => $music,
'political' => $info[0]['political'],
'relationship_status' => $info[0]['relationship_status'],
'sex' => isset($fbme['gender']) ? $fbme['gender'] : '',
'tv' => $television,
'status' => '0',
'created' => $now,
'updated' => $now,
);
//$this->db->insert('demographic', $insData);
}
function getWorkInfoAsString($fbme, $delim = '#', $partDelim = ' | '){
$info = "";
$flag = false;
if (empty($fbme['work'])) return '';
foreach($fbme['work'] as $item){
if ($flag)
$info .= $partDelim;
$flag = true;
$info .= (isset($item['employer']['name']) ? $item['employer']['name'] : '' ). $delim .
(isset($item['location']['name']) ? $item['location']['name'] : '' ). $delim .
(isset($item['position']) ? $item['position']['name'] : '' ). $delim .
(isset($item['start_date']) ? $item['start_date'] : '' ). $delim .
(isset($item['end_date']) ? $item['end_date'] : '' );
}
return $info;
}
function getEducationAsString($fbme, $delim = '#', $partDelim = ' | '){
$info = "";
$flag = false;
if (empty($fbme['education'])) return '';
foreach($fbme['education'] as $item){
if ($flag)
$info .= $partDelim;
$flag = true;
$info .= (isset($item['school']['name']) ? $item['school']['name'] : '' ). $delim .
(isset($item['year']['name']) ? $item['year']['name'] : '');
}
return $info;
}
function getArrayDataAsString($data, $delim = '#', $partDelim = ' | '){
$info = "";
$flag = false;
foreach($data as $item){
if ($flag)
$info .= $partDelim;
$flag = true;
$info .= $item['name'];
}
return $info;
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Facebook User's Demographic Data Collection | Thinkdiff.net</title>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '<?=$fbconfig['appid' ]?>', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
function login(){
document.location.href = "<?=$config['baseurl']?>";
}
function logout(){
document.location.href = "<?=$config['baseurl']?>";
}
</script>
<h3>Facebook User's Demographic Data Collection | Thinkdiff.net</h3>
<?php if (!$fbme) { ?>
You've to login using FB Login Button to see your demographic data
<?php } ?>
<p>
<fb:login-button autologoutlink="true" perms="email,publish_stream,offline_access,user_birthday,user_location,user_work_history,user_religion_politics,user_relationships"></fb:login-button>
</p>
<!-- all time check if user session is valid or not -->
<?php
if ($fbme){
echo '<pre>';
print_r($insData);
echo '</pre>';
}
?>
</body>
</html>
Hope this code will help you to quickly integrate in your project. This data collection code will work in both canvas application and fbconnect base application. You can modify the code easily to get customize data. But fyi this code doesn’t collect all the information of facebook user rather some basic and essential information
And don’t forget extended permission list. I provided this list of permissions as I needed to collect above data.
<fb:login-button autologoutlink="true" perms="email,publish_stream,offline_access,user_birthday,user_location,user_work_history,user_religion_politics,user_relationships"></fb:login-button>







Great tutorial, i was having problems in getting users data with new api, but this article has done the trick. Thanks brother
This is a really informative tutorial! It’s very well written and provides some of the basics that are needed to access Facebook’s data and store the information. It’s a main reason why it’s absolutely scary the amount of data that application developers can get about Facebook users. If I ever decide to offer Facebook as an API on The Easy API – http://theeasyapi.com – then I will be coming back to this article to ensure that I can make accessing this data easier.
Nice work, and very professional.
I’m pretty sure this is against the terms of service of facebook.
@Adam, how you’re pretty sure??!! Visit this link http://developers.facebook.com/policy/ and check
III. Storing and Using Data You Receive From Us
1. You must give users control over their data by posting a privacy policy that explains what data you collect, and how you will use, store, and/or transfer their data.
2. You may cache data you receive from the Facebook API in order to improve your application’s user experience, but you should try to keep the data up to date.
Are you sure about the Facebook TOS – I thought you could only store the FBUID
Facebook changed there TOS. Why not you read that carefully and find yourself?
Nice! But where is the fbmain.php script that’s included at the beginning?
In this article http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/ you’ll find fbmain.php source code.
This is a really informative tutorial!
How can i unset the Facebook cookies ?
I am using the code above in my logout.php file:
setcookie('fbs_'.$appId, "", time() - 36000);
unset($_COOKIE['fbs_'.$appId]);
but it’s not working.
Just a question Mahmud,
If my website post is getting ‘likes’ is it possible to see the data of the people who ‘liked’ that post? The intent is to get better demographics of the people liking the post.
thanks
Azzam
I found no way, if you explore any solution let me know. So that I can share with my blog readers.
Getting more info on this is interesting and whether it can be made into some kind of tangible feature or service using the api:
http://developers.facebook.com/docs/insights/#odata
Hi sir,
I need to get the friends contact information like mobile number and email if acess is allowed and also birthday of my friends.Please help to solve this in java.thank u in advance
Hi,
Can u run my url http://173.203.104.63/fbconnect/
i get error , i dont know how to solve it.
kinldy help me.
hi…i check your site….i think properly working……bt i can’t get that too..pls help
Hey mahmud, thanks for this wonderful post,really liked it,i want to know,how do you add all that data and save it to my database? sorry but i’m new to this…any help will be appreciated:)
Hello, i think i discussed that in this tutorial to get data about user from facebook and save them in your database.
Hello Mahmud, I’m also having problems storing into my database. My database connects fine but isn’t populated when I run the script. I’m not sure if all I was supposed to do was remove the // from //$this->db->insert(‘demographic’, $insData);
First check, if you got the data successfully from facebook or not.
Excellent tutorial, as the rest have been.
Quick question, i was able to print the $insData array with no problems.
However, I have not found any code that will allow me to inset the array into my database.
You have included “$this->db->insert(‘demographic’, $insData);”, but I am unable to locate any other php code that will actually insert it correctly.
Any help would be appreciated.
Thanks a lot.
hi….how to check whether i get data or not
Hi mahmud…….your facebook examples are great and i have become a true fan of this site…..i am developing facebook connect based on your explanation..when i am accessing the home feed in facebook ,i am getting in Json format and i dont know how to parse it ans show it in a representable format…can you please help me on that
http://www.php.net/manual/en/function.json-decode.php
Hi Friend,
I am developing a website uising your Facebook/Twitter/LinkedIn connect API. Here I am able to store and use session/keys for LinkedIN and Twitter but not for Facebook. I want to store the permanet session of a user in my databse so that he dont need to connect everytime. Please help me…. thanks
You can use facebook’s latest library and get access_token of user and save them in database.
hello
How can I do so using fql query?
Hello there! I could have sworn I’ve been to this blog before but after checking through some of the post I realized it’s new to me. Anyways, I’m definitely delighted I found it and I’ll be book-marking and checking back frequently!
i’ve always relied on every implementation that you’ve presented… must i admit, it’s brilliant!.. and reliable..
i’ve been using facebook PHP API for quite some time, now.. however, i’ve now hit a brick wall when it comes to offline_access permission…
the part where i take care of the website login is as follows:
$loginUrl = $facebook->getLoginUrl(array(‘next’ => $login_link));
$loginUrl = $facebook->getLoginUrl(array(‘method’ => ‘permissions.request’));
$loginUrl = $facebook->getLoginUrl(array(‘req_perms’ => ‘email,user_status,publish_stream,offline_access’), $uid);
$loginUrl = $facebook->getLoginUrl(array(‘display’ => ‘popup’));
where $uid=$uid = $facebook->getUser();
i dunno if im missing anyting, has the offline_access been deprecated from the API?… or am i missing a step? i recall it used to work and i used to realize it asked me during “Allow Application”…
thanks in advance,
regrads,
avo
Excellent Article for FB Developers. Expecting more threads related to FB.
Hi Mahmud
I am using your •iSimple – Graph API & IFrame Base Facebook Page Application Development
how can i use this tutorial with it? where do i put this code or how do i call it?
could you please help me?
thank you
Without authentication you can’t retrieve user’s data. so follow iAdvance tutorial and if you understand that tutorial you’ll easily integrate this code to get data.
so
create the database
save this code as database.php put it on the ftp where the fbmain.php, home.php ..etc files are and then
add this line to home.php
include_once “database.php”;
it should do it right?
but where and how the code connects with database? where do i put all the database info, login password server etc?
thank you
I think you should know how to connect database using php.
ok i created the database tables and i connected to the data base
i created a data base called facedatabase but i still don get it
what do i do to insert the info to the database
thank you
Hello nakres,
firstly you have to access userinfo and store in php variable
once you get userinfo then fire insert query and store in your database table
hi
i am using iAdvance, i can get the permissions using that great tutorial. but i have no idea how to insert the data to the database, would you please show me how the insert code would look like so i can try it on this tutorial?
many thanks
i don’t know how
would you be able to show how would it be with your code?
thank you
Hi Mahmud,
A Very informative blog.. I have a query though.. I am trying to create an app which would be kind of a mashup of a person’s social network profile from Linkedin, Facebook , Twitter.
I am finding it difficult to retrieve public data like Work info and education details of a person who is not my friend, even though those data are visible from the Facebook site since it is public. Is there any way out to extract these public data of a non friend profile. Ur help is appreciated.
Thanks..
http://developers.facebook.com/docs/authentication/permissions/ If your user give friend related permission only then you can get data.
Hi.. Thanks for the reply.. I looked over this.. So I have the user and friend related permissions (user_education_history,friends_education_history) but even with this I cant access the public info of people who are not my friends.. I can only acccess info of my friends.
I am really confused as to if a user can see the public info why doesnt Facebook allow to extrac tht info through an app.
Or am i Missing something.. ?
Sandeep
how to get albumls photo in facebook in php ?
hello,
i tried this code but $fbme show empty…
on my server JSON not install ….is this json problem?
do u have any other solution…than Installing JSON?
Forget $fbme, it was facebook PHP sdk 2.0, now you have to update this code by following my latest post.
thanks mahmud,
thanks for your great tutorials…
i got my answer from your forum…
how can i get user mobile number?
Its not possible now as far as I know.
hi guys – thanks for the great code but im having some issues
when I copy the full source code and visit the page, i click on login, signin correctly and allow permissions but then nothing happens ! i dont get redirected by to my baseurl or nothing … any ideas please?
cheers
Hi, I have a question. I’m just wondering that will this method run or not run after October 2012? Thanks,
Where do we connect to our database? I don’t see anywhere that we add our hostname, user, password, or database name? How will the script know where to send the information?
Thanks
i wrote a php fangating program using php sdk, it works fine if the user is https enabled, but if the user is http enabled, it is not working, how to make fangate work even if the user is http enabled ?
Hello its not working on the demo or on my website
Hi Mahmud,
I want to retrieve a user’s friends on facebook. Facebook developer page it says that you can retireve user’s friends using the accesstoken….there is no example since I am new to this FB api thing.
CAn you give an example to retrieve and decode user’s facebook friends using graph API
Regards,
Ravi S.Gohil
Fatal error: Uncaught OAuthException: (#604) Can’t lookup all friends of 1xxxxxx. Can only lookup for the logged in user or the logged in user’s friends that are users of your app.
Please help me ??
Hai mahmud ahsan !
its realy good job.keep rocking…!
Hi , this is really nice link.I am using java graph api to get data from facebook.Till now i did not know about , how to get demographic for public profile. is it possible to get public profile insights data?