I need to add facebook login to my website with double mechanism. First one fires when user click fb login, script checks whether fbid exists in my database and if true sets session. If fbid does not exist script picks up additional data like username and email and then insert fbid into DB. Problem is my code inserts wrong id into db if fbid doesn't exist. Here is my code:
<?php
require_once('lib/facebook.php');
include "db.php";
$statara='';
$config = array(
'appId' => 'xxxxxxxx',
'secret' => 'xxxxxxx',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$fb_user='';
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$fql = 'SELECT uid,name from user where uid = ' . $user_id;
$ret_obj = $facebook->api(array(
'method' => 'fql.query',
'query' => $fql,
));
// FQL queries return the results in an array, so we have
// to get the user's name from the first element in the array.
}
catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
$udj= 'Please <a href="' . $login_url . '">login. redef</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
$login_url = $facebook->getLoginUrl();
$udj= '<a href="' . $login_url . '" id="fblogin">login. redeff</a>';
}
if ($user_id){
$sqlf=mysql_query("SELECT * FROM users where fbid='$user_id'");
$sqlf_num=mysql_num_rows($sqlf);
if ($sqlf_num > 0) { //// Users fbid exist put out his username from db
while($frow=mysql_fetch_array($sqlf)){
$username=$frow['username'];
$fb_user=$username;
}}else{ //// users fbid does not exist so insert him
$fb_user="$user_id to addd";
$sqli=mysql_query("INSERT INTO users(fbid) VALUES('$user_id')");
$stat= "<br><a href='logout.php'>logout ".$fb_user." </a><br>";
}
} else{
$stat="<br>not connected<br>";
}
echo "$udj $fb_user ";
?>