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!
TopUp – awesome library for popups
I was looking for a prettier way of showing a popup window in my site and came across TopUp. It definitely looks nicer than others I've seen and is easy to install and use. It's also free to use
For more info, documentation and demos, check out their site!
Beginning android development
I have decided to start playing with android, maybe develop apps or small games. But before that, it's study time
I looked for a few introductory tutorials and made a list:
- The android essential series on mobile.tutsplus.com
- The android fundamentals series on mobile.tutsplus.com
- The android user interface design series on mobile.tutsplus.com
I also found a book which should also prove useful.
I also looked for frameworks that would ease app development, and discovered Corona. It doesn't seems hard to get used to and there are loads of tuttorials out there to help you, both on their site, or on others.
New version of distance finder
You might remember the previous version of my distance finder. It's a small google maps project that helps you find the distance and the route between two points.
I have decided to improve the layout of the project and add new features. Here's the new version!
A major improvement is the fact that you can now choose a 'via' address for the route. Also, the app is now available in both English and Romanian.
More updates will follow as I'm working on improving it even further!
10 Must Have WordPress Plugins
I compiled a list of very useful wordpress plugins. If you think others should also be added to the list, please let me know!
Akismet
Akismet is probably the best plugin that helps you protect your blog from spammers. It's also really easy to use, you will only need an API key which you will receive after registering.
All in One SEO Pack
All in One SEO Pack is a plugin that helps you optimize your blog for search engines. Really useful is you want other to find you! Of course, the best way to improve your blogs chances of getting found in searches is having useful content!
Clean-Contact
Clean-Contact is one of the many plugins out there for easily creating contact forms for your blog.
FeedBurner FeedSmith
If you have a feedburner feed, you will find this plugin useful. It redirects all traffic from your old feeds to your feedburner feeds so you can track them
Google Analytics
You will most likely want to track how many visitors your blog has and some info about them. Google Analytics is one of the best tools for that. This plugin helps you enable google analytics on all your pages.
Google XML Sitemaps
This plugin generates a sitemap of your blog.
ShareThis
ShareThis is a plugin that allows your readers to easily share your posts with their friends. ShareThis supports many social networks and it's look is easy to customize. I found more plugins that offer basically the same features as SharaThis, but I liked this one the best!
SyntaxHighlighter Evolved
If you are a developer like me and want to share some code pieces in your posts, you will need a SyntaxHighlighter to make your posts look prettier!
Twitter Widget
There are surely lots of wordpress widgets that allow you to show some twitter posts on you blog, but I found Twitter Widget one of the best of them. You only need to fill in your twitter username and the number of posts you want to show and that's it!
WP to Twitter
If you have a Twitter account, you might want to share the link to each new blog post there. WP to Twitter does this for you! To use it, you will have to create a new twitter app on the twitter dev site and copy your credentials from there!
Yodacode programming contest
I've found a new programming contest on yodacode.com. It's not very hard, there are 9 puzzles to finish by the 6th of january. You can solve them in one or more programming languages.
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.

