Organizing Hierarchical Databases
I was researching a better way of organizing the database of one of my projects and came across an interesting article. The article is about organizing hierarchical data in mysql databases. Here it is. The two methods proposed are very well explained and also the advantages and disadvantages of using each method are presented. It helped me get a clear picture of the available methods and pick the best one for my project
How to make website registration easier using facebook accounts part 2
This is the second part the tutorial. If you haven't read the first part yet, you can do so here.
Extra features
Once logged into their accounts, the users can see some info about their friends – the total number of facebook friends they have and how many of their friends are using our app.
Also they have the option to post on their facebook wall.
Get the friends list
For getting the users friends list, we will have to make another call to the Graph API. The code looks like this:
<?php
$graph_url = "https://graph.facebook.com/me/friends?access_token=" . $_SESSION['access_token'];
$friends = json_decode(file_get_contents($graph_url));
$friends_array = $friends->data;
$signedup = 0;
$ids_array = Array();
for($i = 0; $i < count($friends_array); $i++){
$ids_array[] = $friends_array[$i]->{'id'};
}
$q = mysql_query("select facebook_id from `facebook-signup`");
while ($id = mysql_fetch_array($q)){
if (in_array($id['facebook_id'], $ids_array)){
$signedup += 1;
}
}
?>
<div style="margin: 20px;">You have <?php echo count($friends_array);?> friends on facebook, <?php echo $signedup;?> have an account here!</div>
The url we make a request to is: https://graph.facebook.com/me/friends. And all we have to send as parameter is the access token we have stored in session. The API will return a JSON encoded list of friends usernames and facebook ids. We have printed the total number of friends. For checking how many friends have accounts at our app, we make a query to the db to get all the facebook ids and for each of these we checked if they are in the users friends list. As you can see, we have printed out the result of the count.
Posting on wall
To post on a users wall we have to make a post request to the url to call the graph api https://graph.facebook.com/THE_FACEBOOK_ID_OF_THE_USER/feed. We will need the following parameters for the call:
- our app id
- the access token
- the message to post on the wall
We have created a simple form on the page with a textarea for the status and a button for posting it:
<pre>
<form id="fb_form">
<textarea rows="7" style="width: 98%" id="status" name="status"></textarea>
<br/>
<?php
$uid = $_SESSION['uid'];
$usr = mysql_query("select * from `YOUR_TABLE_NAME` where id=$uid");
$usr = mysql_fetch_array($usr);
$url = "https://graph.facebook.com/".$usr['facebook_id']."/feed";
$app_id = "YOUR_APP_ID";
$access_token = $_SESSION['access_token'];
?>
<button id="post_button" onclick="updateStatus('<?php echo $url;?>', '<?php echo $access_token;?>', '<?php echo $app_id;?>')">Post on facebook</button>
</form>
</pre>
As you can see we have set the values we need for the call, app_id and access_token and called the updateStatus javascript function with these parameters.
To get the info about the user (their facebook id we need for the url) we have queried the db. The id of the user was already stored in session (remember we did that when logging the user in) together with the access token. Using the id of the users we have sent a query to the database to get the rest of the user info.
The updateStatus function looks like this:
<pre>
function updateStatus(url, access_token, app_id){
document.getElementById('post_button').disabled = true;
message = document.getElementById('status').value;
var jqxhr = $.post(url, { "access_token": access_token, "message": message, "app_id": app_id },
function(data) {
alert("Status updated successfully!");
document.getElementById('post_button').disabled = false;
document.getElementById('status').value = "";
});
}
</pre>
We have used the jquery library to make a post request. The parameters we sent are the appid, accesstoken and the message that the user wrote. We get the text of the message by getting the value of the textarea.
<pre>message = document.getElementById('status').value; </pre>
Using these values, we make a post request to the server and when the server returns successfully, we show a message to the user to let them know the status was posted.
We also added some code that disabled the post button while the request is made to prevent the user from clicking more than once on it and posting the same message twice. Once the request returns, the button is enabled.
Deleting the account
We have also added a button for users to be able to delete their accounts:
<a onclick="return testDelete();" href="deleteAccount.php?id=<?php echo $usr[id];?>"><button>Delete account</button></a>
When they press the button we will show a popup box to check that they are sure they want to delete their account. We do this by calling the testDelete() js function that looks like this:
function testDelete()
{
return confirm("Are you sure you want to delete your account?");
}
After they confirm, they are redirected to the deleteAccount.php script that does the deletion. The scripts gets the user id and runs the sql query for deleting the user from our db. After deletion, the scripts redirects to the index page.
<?php
$id = $_GET['id'];
$q = mysql_query("delete from `YOUR_TABLE_NAME` where id=$id");
header('Location: index.php');
?>
And that’s it! We have learnt how to add facebook registration/login to our site! Of course, this tutorial only shows basic features, but starting from this you can add whatever features you need.
Conclusion
I hope you enjoyed the tutorial and that you now have a better picture on how to use facebook for user registration. In case you have any questions or comments, please don’t hesitate to ask. I’d be happy to help!
Source Code
I have included an zip file with the complete code for both parts of the tutorial. Don't forget to download the twitter bootstrap folder and place it in the same folder with my source code to view the nice layout. And if you want to test the code, you will have to replace the app_id, app_secret and db related values. You can download the code from here.
How to make website registration easier using facebook accounts
What are we going to build?
In this tutorial we will learn how we can facilitate user registration but letting users register to our site using their facebook accounts. This way, they won’t have to fill in any data, just grant the app access to their facebook account and that’s it! Their new account is created and they can easily login to our website.
We will be making calls to facebooks Graph API in order to retrieve the necessary information. In case you are not familiar with it, you might want to take a look at the documentation to get an idea of what it does.
You can view the working demo of what we are going to build here.
The tutorial will have two parts: the first will cover the basic signup/login issues, the second will cover the extra features we will add to our app (viewing friends info and posting on the wall).
Let’s get started!
Getting started
You would be using this is you have a website that users can register to and you want to make the registration easier for them by allowing them to register with their facebook accounts. In the tutorial, I will only show you how to use facebook accounts for registration, not how to add this to your existing registration. But it shouldn’t be difficult to integrate if you understand the tutorial. If you have questions on that, just ask.
For this tutorial you will need some basic PHP and Javascript knowledge.
Creating a new facebook app
The first thing we have to do is create a new facebook app. To do this, go here and chose to create a new app. You will get to the screen when you have to fill in the app info. The screen will look something like this:
As you can see in the screenshot, you will have to fill in the following:
- A display name for your app
- Your email address
- The domain where the app will be hosted
- The site url – this is the most important value, it is the url of the page where the app will be redirected after facebook authorization. This page will hold the logic for registering new users and loggin in returning users.
So, make sure you fill in the site url correctly and keep in mind the values at the top of the page (app is and app secret) as we will need them later.
And that’s it! You now have a facebook app. Let’s see how we can use it!
Creating the db
Next we have to create the db table to hold the data about our users. Let’s suppose we want to store the following data about our users:
- Username
- Name
You will probably want to store more data in a real application, but these will do for the tutorial.
Apart from these, we will also want to store the facebook id of the users. So our database will look something like this:
The php code for connecting to the database looks like this:
<?php
$server = "YOUR_SERVER_ADDRESS";
$username = "YOUR_USERNAME";
$password = "YOUR_PASSWORD";
$database = "YOUR_DATABASE_NAME";
$connId = mysql_connect($server,$username,$password) or die("Cannot connect to server");
$selectDb = mysql_select_db($database,$connId) or die("Cannot connect to database");
?>
Designing the site
Our demo website will have a few pages:
- index.php – the starting point -the users can choose to signup/login with facebook from here
- welcome.php – the users will be redirected here after creating a new account
- home.php – the main user page, the user will view some info about their facebook friends, have the options to post a new status on facebook and delete their account
I will leave out any design issues. I have chosen to use the twitter bootstrap library to make a nice demo, but you can choose whatever you like for yours. The design on the website is not in the scope of this tutorial.
Signup with facebook
The main page, index.php will hold one button to allow users to signup/login. The code looks like this:
<a href="https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_APP_REDIRECT_URL&scope=publish_stream" title="Signup with facebook"> <button>Signup with facebook</button> </a>
All we have to do in order to do this, is redirect the user to the facebook oauth dialog where they have to allow the usage of our app.
All we have to do is make a call to the url https://www.facebook.com/dialog/oauth and mention a few parameters:
- client_id – your app id - remember the value from when we created the facebook app? Here’s one of the places we need it
- redirect_uri – the url where you want the app the redirect after authenticating with facebook
these two are the only mandatory values
You can see that I added a new one: scope. A simple app allows you only to access the basic info that users made public from their facebook accounts. If you want to access more info or be able to use their account in other ways, like posting on their wall from you app and such, you will need to be granted special permissions by the user. This is why we use the scope parameter, to specify the permissions we need for our app. I added the publish_stream permission, which will allow us to post on user wall. You can view the complete list of permission here.
When clicking on the button, the user will get redirected to the authentication screen from facebook and after they grant the permissions, they will be redirected to our app. They will receive a code which we will have to use in order to get an access token for the user. Why do we need an access token? Well, every request for user data that we want to make to facebook will need this access token. So here’s how we get it:
<pre> $app_id = "YOU_APP_ID"; $app_secret = "YOUR_APP_SECRET"; $my_url = "YOUR_APP_REDIRECT_URL"; $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code . "&scope=publish_stream"; $response = @file_get_contents($token_url); $params = null; parse_str($response, $params); </pre>
We again need to app id and secret. With these and the redirect url (the one we set when creating the app) and the code we received we will make a new request to facebook to get the access token. After executing the code above, the access token will be stored in $params['access_token'].
With this, we can make a request to the facebook graph api and get the user data, like so:
<pre> $graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token']; $user = json_decode(file_get_contents($graph_url)); $username = $user->username; $email = $user->email; $facebook_id = $user->id; </pre>
We will get the data we decided to use for the app: username, facebook_id and email address.
What we have to do next is check whether the user has already registered for our app. We will check if the facebook_id is already in our db. If it is, then the user already has an account and they will be redirected to their home page (they will be logged into their account). If the user is not in db, then we will add them and redirect them to the welcome page. Like this:
// check if user in db => login
$result = mysql_query("select * from `YOUR_TABLE_NAME` where `facebook_id`='$facebook_id'");
if (mysql_num_rows($result) == 1)
{
$usr = mysql_fetch_array($result);
$_SESSION['username'] = $usr['username'];
$_SESSION['uid'] = $usr['id'];
$_SESSION['access_token'] = $params['access_token'];
?>
<script>
top.location.href='home.php'
</script>
<?php
}
else // if user not in db
{
$join_date = date('Y-m-d h:i:s');
$query = mysql_query("INSERT INTO `YOUR_TABLE_NAME` (username, email, facebook_id, join_date)
VALUES ('$username', '$email', '$facebook_id', '$join_date')");
$_SESSION['uid'] = mysql_insert_id();
$_SESSION['username'] = $username;
$_SESSION['access_token'] = $params['access_token'];
?>
<script>
top.location.href='welcome.php'
</script>
<?php
}
As you can see, we have also set some variables in session. We will need these to check the id/username of the logged in user and the access token. Remember I said we need this for every request we will make to the Facebook Graph API! And that’s it!
For more info, you can see the facebook documentation on authentication here.
And that's it for today, the part 2 of the tutorial is available here!
How to use Google Maps Street View
My fourth google maps tutorial was published on 1stwebdesigner.com. The tutorial covers another of google maps features, street view.
I have built an app for this tutorial, an interactive visit of Paris. You’ll be able to visit certain locations, walk through Paris or take virtual tours.
You can read the tutorial here and also play with the app.
You can also download the source code.
How to convert between ANSI and UNICODE strings?
Useful C++ code for converting between ANSI an UNICODE strings:
Ansi to Unicode:
char *ansistr = "Hello"; int a = lstrlenA(ansistr); BSTR unicodestr = SysAllocStringLen(NULL, a); ::MultiByteToWideChar(CP_ACP, 0, ansistr, a, unicodestr, a); ::SysFreeString(unicodestr);
Unicode to Ansi:
BSTR unicodestr = 0;
SomeCOMFunction(&unicodestr);
int a = SysStringLen(unicodestr)+1;
char *ansistr = new char[a];
::WideCharToMultiByte(CP_ACP,
0,
unicodestr,
-1,
ansistr,
a,
NULL,
NULL);
delete[] ansistr;
::SysFreeString(unicodestr);
Creating an Interactive Travel Map using the Google Maps API
I've played again with the google maps api and started working on an interactive travel map. The idea is that everyone can add new locations and view the locations added by others.
I've also written a tutorial about this, you can read it here.
How to integrate facebook in your site using the facebook javascript sdk
If you are looking for integrating facebook in your site, you should check out the facebook javascript sdk. I've written a tutorial that shown how to use the sdk. It's been published on 1stwebdesigner.com.
Other improvements to my distance finder
I've added some more features to my distance finder. You can now share your search results with your friends on twitter. I've used twitter's @anywhere to do this.
If you want to find out how I did this, I've also written a tutorial.
I'm planning to also integrate facebook so you'll be able to share your results on there too
How to prevent contact form spam
Yes, you can also get spammed through the contact form on your site! How can you prevent that? It’s pretty easy! Add a method of checking if the form is filled by one of your site’s visitors and not by a bot.
There are more ways of doing this. One of them is to use a captcha (a small text shown in an image that the user has to fill in the form). Here’s a tutorial on how to use one of these.
I will show you another way of doing this: having the user fill in the result of a mathematical operation. If the correct result is filled in, the form is sent to you.
You can see a demo of this on my website.
Here’s how we’ll do this:
Suppose we have the following contact form (in the file named 'contact.php'):
<form action="send.php" id="contact" name="contact" method="post"> <table align=left> <tr> <td>Name:</td> <td><input type="text" id="name" name="name"></td> </tr> <tr> <td>Email:</td> <td><input type="text" id="email" name="email"></td> </tr> <tr> <td>Message:</td> <td><textarea rows="5" cols="40" id = 'message' name = 'message'></textarea></td> </tr> <tr> <td><input type="submit" value="Send message"></td> </tr> </table> </form>
When the user presses the submit button, the 'send.php' script will be called. This script sends an email with the info that was filled in the form.
We will have to add the part to verify the user.
We will ask the user to fill in the result of a mathematical operation. The user will have to add the randomly generated numbers between 1 and 15.
Here’s the code to generate the two numbers and compute the correct sum:
<?php srand(time()); $nr1 = (rand()%14)+1; $nr2 = (rand()%14)+1; $sum = $nr1 + $nr2; ?>
We will now display the numbers to the user and ask him/her to fill in the result in a new input field. We’ll add a new row in the table which holds the form:
<tr> <td>Are you human?<br/>What is the result of <?php echo $nr1;>+<?php echo $nr2;>?</td> <td><input type="text" id="nr" name="nr"></td> </tr>
We’ll also add a hidden field to the form to hold the correct sum.
These are all the changes we have to make to the contact form.
We’ll also have to modify the send.php script to check the sum before sending the email:
$nr = $_POST[nr];
$sum = $_POST[sum];
if ($nr != $sum)
header('Location: contact.php?msg=wrong');
else
// add code to send the mail with the form data
If the sum from the hidden field is equal to the one filled in by the user, the email is sent. If not, the user is redirected to the 'contact.php' page and an error message is shown. Here’s what we’ll have to add to the contact.php file to show the error message:
if(isset($_GET['msg']))
{
if ($_GET['msg'] == 'wrong')
echo "<p> <font color=red>The result you entered is wrong</font>";
}
And that’s it!
Let me know if you have questions or comments!
How to add favicons to your site or wordpress blog
What are favicons? They are the tiny icons that you can see next to a site's title in your browser window. You can also see them when bookmarking a site, next to it's title.
Adding one to your website is really simple! You just have to find an image you like, resize it to 16pixels x 16pixels (the custom size for favicons). Name the image "favicon.ico" and place it in your website's root folder. And you're done!
Adding a favicon to your wordpress blog is a little bit more complicated. You will have to add the icon to your templates main folder (your blog/wp-content/themes/default) and edit the "header.php" file of your current theme. You will have to add this line in the
<head></head>
tags:
<link rel="shortcut icon" href="<?php bloginfo('template_directory'); ?>/favicon.ico" />
And that's it!

