我正在尝试从我的PHP应用程序获取用户数据,然后将这些数据存储到我的数据库中。在我将我的应用程序上传到Facebook之前,我想知道这种形式的代码是否写得不错。 以下是我使用的代码。
<head>
<?php
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'xxxx',
'secret' => 'xxxxxx',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
</head>
<body>
<?php
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 name, first_name, last_name, birthday_date, sex,
education, locale, activities from user where uid = ' . $user_id;
$ret_obj = $facebook->api(array(
'method' => 'fql.query',
'query' => $fql,
));
mysql_query("INSERT INTO table(firstname, lastname, birthday, sex,
education, local, activities) VALUES($ret_obj['first_name'], $ret_obj['last_name'],
$ret_obj['birthday_date'], $ret_obj['sex'], $ret_obj['education'],
$ret_obj['locale'], $ret_obj['activities']) ");
// FQL queries return the results in an array, so we have
// to get the user's name from the first element in the array.
echo '<pre>Name: ' . $ret_obj[0]['name'] . '</pre>';
} 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();
echo 'Please <a href="' . $login_url . '">login.</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();
echo 'Please <a href="' . $login_url . '">login.</a>';
}
?>
</body>