Well today we are going to create a Quiz application for FB (ya ya already there are lots of quiz app floating on FB
so why not one more)
This Tutorial is going to be very brief and point to point because I am very bad in explaining things
..
If you have any comment or ways to improve it, just leave me a comment!
1) Facebook Account
2) Hosting (PHP and MySql Support needed for this demo)
First you need to log in to the Facebook Developer application: Go to the Facebook Developer App. After following the link, click “Allow” to let the Developer application access your profile.. Then click on the Set Up New Application (Highlighted in image given below for you, yes you)

After clicking “setup new application” you will get a page asking for Application name and agree – disagree radio buttons for their terms. Give your application a nice name and agree to their terms.

Weird Application name! yes i know.
After submitting you will see a page for editing basic info of the application. everything is self explanatory
I told you i am very bad in explaining (need a lady teacher.. cute one
)
Your API key: this key identifies your application to Facebook. You pass it with all your API calls.
Your application secret: Facebook uses this key to authenticate the requests you make. As you can tell by its name, you should never share this key with anyone.

Click on the “Canvas” link. Your canvas page is the application area within Facebook; the name is added to the URL and will look like this: http://apps.facebook.com/[YOUR APP NAME]. The callback URL points to the server hosting the app files. Please look at the image given below (em.. I am getting polite now, wasn’t i before)
Render Method: Choose whether you will render your canvas page in an iframe or with FBML. For this APP we will be using FBML
Submit After filling all the details.

ok lets start some PHP, create two files “index.php” , “config.php” and a folder “facebook”. Download the client libs of your choice from Facebook client libraries . For this demo I’ll be using the official PHP client.
Extract the content of the php folder(from Facebook’s official php client) in folder facebook of your application.
paste the given code in your config.php file. Do not forget to change database settings and Facebook constants i.e API , Secret etc..
<?php
// ** MySQL settings ** //
define('DB_NAME', 'quiz'); // The name of the database
define('DB_USER', 'root'); // Your MySQL username
define('DB_PASSWORD', ''); // ...and password
define('DB_HOST', 'localhost'); // 99% chance you won't need to change this value
// ** Facebook settings ** //
define('API_KEY', 'Your API'); // Change this to a your Facebook API key.
define('SECRET', 'Your Secret Key'); // Change this to a your Facebook secret key.
define('APP_NAME', 'Drum Your Dialogue Knowledge!'); // Your application name
define('APP_URL', 'dialoguedrums');// App. url after the http://apps.facebook.com/
/* That's all, stop editing! Happy Facebooking
. */
require_once('facebook/facebook.php');
mysql_connect(DB_HOST, DB_USER,DB_PASSWORD);
@mysql_select_db(DB_NAME) or die( "Unable to select database");
?>
Before creating Facebook quiz application lets create a simple PHP quiz first.
<?php
session_start();
require('config.php');
if($_GET['act'] == '')
{
$quizQuery = "SELECT * FROM questions";
$quizResult = mysql_query($quizQuery);
$rowCount = mysql_num_rows($quizResult);
$_SESSION['totalQuestions'] = $rowCount;
if($rowCount &amp;amp;amp;gt;= 1)
{
echo '<form action="?act=answer" method="post">';
while($quizData = mysql_fetch_assoc($quizResult))
{
echo "<h2>$quizData[quiz]</h2>";
$answerQuery = "SELECT * FROM answers WHERE question_id='$quizData[id]'";
$answerResult = mysql_query($answerQuery);
if(mysql_num_rows($answerResult) >= 1)
{
while($answerData = mysql_fetch_assoc($answerResult))
{
echo "<input type='radio' name='answer-$quizData[id]' value='$answerData[id]'> $answerData[answer]<br/>";
}
}
}
echo "<br/><input type='submit' value='Submit' name='sny-fb-app'/>";
echo '</form>';
}
}
elseif(isset($_POST['sny-fb-app']) && $_GET['act']=='answer')
{
$quizIdQuery = 'SELECT id FROM questions';
$quizIdResult = mysql_query($quizIdQuery);
$rowCount = mysql_num_rows($quizIdResult);
if($rowCount >= 1)
{
while($quizIdData = mysql_fetch_assoc($quizIdResult))
{
$answerId = (int)$_POST['answer-' . $quizIdData['id']];
if(!empty($answerId))
{
$answerCheckQuery = "SELECT correct FROM answers WHERE id=$answerId";
$answerCheckResult = mysql_query($answerCheckQuery);
$correctAnswers = 0;
if(mysql_num_rows($answerCheckResult) &amp;amp;amp;gt;= 1)
{
$answerCheckData = mysql_fetch_row($answerCheckResult);
if($answerCheckData[0]==='yes')
{
$correctAnswers++;
}
}
}
}
$percentage = $correctAnswers/$rowCount * 100;
}
echo $percentage.'%';
}
?>;

Our Plain and Simple PHP Application
Yes time for Facebook API integration. Create an object for Facebook API and now you are ready to interact with it.
$fb = new Facebook(API_KEY, SECRET);
Our application can be accessed from Facebook only. Nobody can access it directly like http://yourhost.com/youFbApplication/ for that we can use require_frame() function of Facebook API.
$fb->require_frame();
require_login() function can be used to force user to login firs if not logged in already, function returns ID of the logged in user.
$userId = $fb->require_login();
ok if we want to Invite friends functionality we can use FQL and FBML(Facebook Markup Language) for that
/*Multiple Friend Invitaion*/
$fql = 'SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1="' .
$userId . '") AND has_added_app=1';
$_friends = $fb->api_client->fql_query($fql);
// Extract the user ID’s returned in the FQL request into a new array.
$friends = array();
if (is_array($_friends) && count($_friends))
{
foreach ($_friends as $friend)
{
$friends[] = $friend['uid'];
}
}
// Convert the array of friends into a comma-delimeted string.
$friends = implode(',', $friends);
$content = "<fb:name uid=\"" . $userId . "\" firstnameonly=\"true\" shownetwork=\"false\"/> has played <a href=\"http://apps.facebook.com/" .
APP_URL . "/\">" . APP_NAME .
"</a> and thought it's so cool even you should try it out!\n" .
"<fb:req-choice url=\"" . $fb->get_add_url() . "\" label=\"Play " . APP_NAME .
"\"/>";
?>
<fb:request-form action="?act=done" method="post" type="<? echo APP_NAME; ?>" content="<? echo
htmlentities($content, ENT_COMPAT, 'UTF-8'); ?>"> <fb:multi-friend-selector actiontext="Here are your friends who don't have <? echo
APP_NAME ?> yet. Invite whoever you want -it's free!" exclude_ids="<? echo
$friends; ?>" /> </fb:request-form>
The Wall story request feature is implemented as a popup using FBJS – the subset of javascript allowed on Facebook canvas pages. It is slightly more complex than that unfortunately – you need to create a feed template first to describe the format of the story that will appear on users newsfeeds.
Go to the template editor tool to begin. We’ll create a simple feed that shows some images and invites people to try the quiz.
Create a One Line Story template
One line template code.
{*actor*} played {*app_name*} quiz.
Sample Template Data.
{ "app_name":"my Application", "quiz_result":"80%"}

Create a Short Story template
Short story template title code.
{*actor*} took the {*app_name*} quiz and got the result: {*quiz_result*}..

Skip the create action link form and register the template bundle after it go to Registered Template Console .

<?php
session_start();
require('config.php');
$fb = new Facebook(API_KEY, SECRET);
$fb -> require_frame();
$userId = $fb -> require_login();
if($_GET['act'] == '')
{
$_SESSION['percentage']='';
$quizQuery = "SELECT * FROM questions";
$quizResult = mysql_query($quizQuery);
$rowCount = mysql_num_rows($quizResult);
if($rowCount >= 1)
{
echo '<form action="?act=answer" method="post">';
while($quizData = mysql_fetch_assoc($quizResult))
{
echo "<h2>$quizData[quiz]</h2>";
$answerQuery = "SELECT * FROM answers WHERE question_id='$quizData[id]'";
$answerResult = mysql_query($answerQuery);
if(mysql_num_rows($answerResult) >= 1)
{
while($answerData = mysql_fetch_assoc($answerResult))
{
echo "<input type='radio' name='answer-$quizData[id]' value='$answerData[id]'> $answerData[answer]<br/>";
}
}
}
echo "<br/><input type='submit' value='Submit' name='sny-fb-app'>";
echo '</form>';
}
}
elseif(isset($_POST['sny-fb-app']) && $_GET['act']=='answer')
{
$quizIdQuery = 'SELECT id FROM questions';
$quizIdResult = mysql_query($quizIdQuery);
$rowCount = mysql_num_rows($quizIdResult);
if($rowCount >= 1)
{
while($quizIdData = mysql_fetch_assoc($quizIdResult))
{
$answerId = (int)$_POST['answer-' . $quizIdData['id']];
if(!empty($answerId))
{
$answerCheckQuery = "SELECT correct FROM answers WHERE id=$answerId ";
$answerCheckResult = mysql_query($answerCheckQuery);
$correctAnswers = 0;
if(mysql_num_rows($answerCheckResult) >= 1)
{
$answerCheckData = mysql_fetch_row($answerCheckResult);
if($answerCheckData[0]==='yes')
{
$correctAnswers++;
}
}
}
}
$percentage = $correctAnswers/$rowCount * 100;
}
$_SESSION['percentage'] = $percentage;
/*Multiple Friend Invitaion*/
$fql = 'SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1="' .
$userId . '") AND has_added_app=1';
$_friends = $fb->api_client->fql_query($fql);
// Extract the user ID’s returned in the FQL request into a new array.
$friends = array();
if (is_array($_friends) && count($_friends))
{
foreach ($_friends as $friend)
{
$friends[] = $friend['uid'];
}
}
// Convert the array of friends into a comma-delimeted string.
$friends = implode(',', $friends);
$content = "<fb:name uid=\"" . $userId . "\" firstnameonly=\"true\" shownetwork=\"false\"/> has played <a href=\"http://apps.facebook.com/" .
APP_URL . "/\">" . APP_NAME .
"</a> and thought it's so cool even you should try it out!\n" .
"<fb:req-choice url=\"" . $fb->get_add_url() . "\" label=\"Play " . APP_NAME .
"\"/>";
?>
<fb:request-form action="?act=done" method="post" type="<? echo APP_NAME; ?>" content="<? echo
htmlentities($content, ENT_COMPAT, 'UTF-8'); ?>"> <fb:multi-friend-selector actiontext="Here are your friends who don't have <? echo
APP_NAME ?> yet. Invite whoever you want -it's free!" exclude_ids="<? echo
$friends; ?>" /> </fb:request-form>
<?php
/*Multiple Friend Invitaion END*/
}
elseif($_GET['act']=='done')
{
/*Wall Story Posting*/
?>
<h1>Thanks For Playing <a href="http://apps.facebook.com/<?php echo APP_URL ?>"><?php echo APP_NAME?></a></h1>
<script type="text/javascript">
var tpl_data={"images":[{"src":"http://mypaaji.com/fb/images/kaalia_amitabh.jpg", "href":"http://apps.facebook.com/<?php echo APP_URL ?>"},{"src":"http://mypaaji.com/fb/images/20pari.jpg","href":"http://apps.facebook.com/<?php echo APP_URL ?>"},{"src":"http://mypaaji.com/fb/images/lh11sholay.jpg", "href":"http://apps.facebook.com/<?php echo APP_URL ?>"},{"src":"http://mypaaji.com/fb/images/mrindia.jpg","href":"http://apps.facebook.com/<?php echo APP_URL ?>"}],"app_name":"<a href='http://apps.facebook.com/<?php echo APP_URL ?>'><?php echo APP_NAME ?></a>","quiz_result":"<?php echo $_SESSION['percentage'] ?>"};
var user_msg = {"value":""};
var share_msg = "share with your friends";
Facebook.showFeedDialog(125793055361, tpl_data, "", "", null, share_msg, user_msg);
</script>
<?php
/*Wall Story Posting END*/
}
?>
Share Some Love