9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Monday, May 20, 2013

Facebook Like System with Jquery, MySQL and PHP.

Facebook like system is one of the best implementation in social network systems, may be in future based on like data Facebook going to launch semantic search engine. In this post I have explained how to implement like/unlike system database design and web implementation with PHP and jquery.

Facebook Like System with Jquery, MySQL and PHP.


Download Script
     Live Demo

Database Design
To build the message conversation system, you have to create three tables such as Users, Conversation and Conversation_Reply. This following image generated by using Mysql Workbench tool.

Users Table
User table contains all the users registration details.
CREATE TABLE `users` (
`uid` int NOT NULL PRIMARY KEY AUTO_INCREMENT ,
`username` varchar(25) NOT NULL UNIQUE,
`password` varchar(50) NOT NULL ,
`email` varchar(100) NOT NULL
);

Data will store in following way, here the password data encrypted with MD5 format.

Facebook Like System with Jquery, MySQL and PHP.

Facebook Like System with Jquery, MySQL and PHP.

Messages Table
This table contains user status messages data. Here uid_fk  is the FOREIGN KEY to REFERENCES users.uid
CREATE TABLE   `messages` (
`msg_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`message` varchar(200) NOT NULL,
`uid_fk` int(11) NOT NULL,
`like_count` int(11) DEFAULT NULL,
`created` int(11) DEFAULT NULL,
FOREIGN KEY (uid_fk) REFERENCES users(uid)
);

Facebook Like System with Jquery, MySQL and PHP.

Facebook Like System with Jquery, MySQL and PHP.

Message Like Table
Contains all user message likes relation data. Here uid_fk is FOREIGN KEY to REFERENCES users.uid and msg_id_fk is FOREIGN KEY to REFERENCES messages.msg_id
CREATE TABLE `message_like` (
`like_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`msg_id_fk` int(11),
`uid_fk` int(11) NOT NULL,
`created` int(11) NOT NULL,
FOREIGN KEY (uid_fk) REFERENCES users(uid),
FOREIGN KEY (msg_id_fk) REFERENCES messages(msg_id)
);
Facebook Like System with Jquery, MySQL and PHP.

Facebook Like System with Jquery, MySQL and PHP.

HTML Code
Simple HTML code.
<div class="stbody">
<div class="stimg"><img src="userprofile.jpg"/></div>
<div class="sttext">
<b>Srinivas Tamada</b>: Status Message
<div class="sttime">48 seconds ago</div>

<div><a href="#" class="like" id="like103" title="Like" rel="Like">Like</a>
</div>

<div class='likeUsers' id="likes103"><span id="you103"><a href="#">You</a>,</span> <a href="#">Srinivas</a>, <a href="#">Harsha</a> and 20 other friends like this.
</div>

</div>
</div>

PHP Code
To show Like or Unlike from message_like table based on message ID.
<div>
<?php
$msg_id='103'; //Message id
$uid='1'; //Message user id.
$q=mysqli_query($db,"SELECT like_id FROM message_like WHERE uid_fk='$uid' and msg_id_fk='$msg_id' ");
if(mysqli_num_rows($q)==0)
{
echo '<a href="#" class="like'" id="like'.$msg_id.'" title="Unlike" rel="Unlike">Unlike</a>';
 }
else
{
echo '<a href="#" class="like" id="like'.$msg_id.'" title="Like" rel="Like">Like</a>';
} ?>
</div>

PHP Code
This code will display likes users details from users and message_like tables based on message ID.
<?php
if($like_count>0)
{
$query=mysqli_query($db,"SELECT U.username,U.uid FROM message_like M, users U WHERE U.uid=M.uid_fk AND M.msg_id_fk='$msg_id' LIMIT 3");
?>
<div class='likeUsers' id="likes<?php echo $msg_id ?>">
<?php
$new_like_count=$like_count-3;
while($row=mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$like_uid=$row['uid'];
$likeusername=$row['username'];
if($like_uid==$uid)
{
echo '<span id="you'.$msg_id.'"><a href="'.$likeusername.'">You</a>,</span>';
}
else
{
echo '<a href="'.$likeusername.'">'.$likeusername.'</a>';

}
echo 'and '.$new_like_count.' other friends like this';
?>
</div>
<?php }
else {
echo '<div class="likeUsers" id="elikes'.$msg_id.'"></div>';
} ?>


JavaScript
Contains javascipt code. $(".like").click(function(){}- like is the class name of the like/unlike anchor tag. Using $(this).attr("id") calling anchor tag ID value.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$('.like').die('click').live("click",function()
{
var ID = $(this).attr("id");
var sid=ID.split("like");
var New_ID=sid[1];
var REL = $(this).attr("rel");
var URL='message_like_ajax.php';
var dataString = 'msg_id=' + New_ID +'&rel='+ REL;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function(html){

if(REL=='Like')
{
$("#youlike"+New_ID).slideDown('slow').prepend("<span id='you"+New_ID+"'><a href='#'>You</a> like this.</span>.");
$("#likes"+New_ID).prepend("<span id='you"+New_ID+"'><a href='#'>You</a>, </span>");
$('#'+ID).html('Unlike').attr('rel', 'Unlike').attr('title', 'Unlike');
}
else
{
$("#youlike"+New_ID).slideUp('slow');
$("#you"+New_ID).remove();
$('#'+ID).attr('rel', 'Like').attr('title', 'Like').html('Like');
}

}
});
</script>

message_like_ajax.php
Contains PHP code to update Like or Unlike data.
<?php
include 'db.php';
if(isSet($_POST['msg_id']) && isSet($_POST['rel']))
{
$msg_id=mysqli_real_escape_string($db,$_POST['msg_id']);
$rel=mysqli_real_escape_string($db,$_POST['rel']);
$uid=$session_uid; // User login session id
if($rel=='Like')
{
//---Like----
$q=mysqli_query($db,"SELECT like_id FROM message_like WHERE uid_fk='$uid' and msg_id_fk='$msg_id' ");
if(mysqli_num_rows($q)==0)
{
$query=mysqli_query($db,"INSERT INTO message_like (msg_id_fk,uid_fk) VALUES('$msg_id','$uid')");
$q=mysqli_query($db,"UPDATE messages SET like_count=like_count+1 WHERE msg_id='$msg_id'") ;
$g=mysqli_query($db,"SELECT like_count FROM messages WHERE msg_id='$msg_id'");
$d=mysqli_fetch_array($g,MYSQLI_ASSOC);
echo $d['like_count'];
}
}
else
{
//---Unlike----
$q=mysqli_query($db,"SELECT like_id FROM message_like WHERE uid_fk='$uid' and msg_id_fk='$msg_id' ");
if(mysqli_num_rows($q)>0)
{
$query=mysqli_query($db,"DELETE FROM message_like WHERE msg_id_fk='$msg_id' and uid_fk='$uid'");
$q=mysqli_query($db,"UPDATE messages SET like_count=like_count-1 WHERE msg_id='$msg_id'");
$g=mysqli_query($db,"SELECT like_count FROM messages WHERE msg_id='$msg_id'");
$d=mysqli_fetch_array($g,MYSQLI_ASSOC);
echo $d['like_count'];
}
}
}
?>

Final PHP Code
Complete Like/Unlike system.
<?php
$query=mysqli_query($db,"SELECT U.username, U.uid, M.msg_id, M.message FROM users U, messages M WHERE U.uid=M.uid_fk and U.uid='$sessions_uid'");
while($row=mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$msg_id=$row['msg_id'];
$message=$row['message'];
$username=$row['username'];
$uid=$row['uid'];
?>

<div class="stbody">
<div class="stimg"><img src="userprofile.jpg"/></div>
<div class="sttext">
<b>Srinivas Tamada</b>: Status Message
<div class="sttime">48 seconds ago</div>
<div>
<?php
$q=mysqli_query($db,"SELECT like_id FROM message_like WHERE uid_fk='$uid' and msg_id_fk='$msg_id' ");
if(mysqli_num_rows($q)==0)
{
echo '<a href="#" class="like'" id="like.$msg_id.'" title="Unlike" rel="Unlike">Unlike</a>';
 } else {
echo '<a href="#" class="like" id="like.$msg_id.'" title="Like" rel="Like">Like</a>';
} ?>
</div>

<?php if($like_count>0) {
$query=mysqli_query($db,"SELECT U.username,U.uid FROM message_like M, users U WHERE U.uid=M.uid_fk AND M.msg_id_fk='$msg_id' LIMIT 3");
?>
<div class='likeUsers' id="likes<?php echo $msg_id ?>">
<?php
$new_like_count=$like_count-3;
while($row=mysqli_fetch_array($query))
{
$like_uid=$row['uid'];
$likeusername=$row['username'];
if($like_uid==$uid)
{
echo '<span id="you'.$msg_id.'"><a href="'.$likeusername.'">You</a></span>';
}
else
{
echo '<a href="'.$likeusername.'">'.$likeusername.'</a>';

}
echo 'and '.$new_like_count.' other friends like this';
?>
</div>
<?php }
else {
echo '<div class="likeUsers" id="elikes'.$msg_id.'"></div>';
} ?>
</div>
</div>
<php } ?>

db.php
Database configuration file, modify username, password and database values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
Comments
{ 68 comments }
Balaji said...

This is fantastic man, thank u...

SANGRAM BARGE said...

nice post dude.You're genius

Talha Akbar said...

Well, don't you think mysql_ functions are deprecated ?

Danielvergara said...

I get errors when I try it, download the file and did not contain php script. Might complete upload am a novice in php and jquery.

Thanks before hand!

Anonymous said...

Plz do a pdo tutorial.

choowit boondao said...

many thanks

Anonymous said...

Talha Akbar: well, you can use PDO's if mysql_ functions are troubling you...

santoshsarma jayanthi said...

Nice tutorial .. ! Thanks Srinivas !

Ash4rose said...

awsm post....

carl lindberg said...

mysql_query is deprecated unfortunetly since it's so handy instead mysqli_query($databaselink, $query); could be used. http://php.net/manual/en/function.mysql-query.php

carl lindberg said...

nice post by the way :)

Siva prabu said...

Thanks dear brother ! !

Anonymous said...

so nice

phphunger said...

Simply superb.......

Anonymous said...

MD5? Seriously?

Aashish Sahni said...

dude,...thanks for the post!!

kocu ogebz said...

wow nice post. thanks :)

Anonymous said...

wow

Sharath said...

Excellent. Initilly had issues with jquery but sorted it. Thanks a lot

JOHN kidman said...

This information is great for PHP project.

Mkhuda said...

Hmm.. wonderfull !
Thanks for your tutorial , i wanna try it !

Haddock said...

Can this be termed as a competition for FB?
Congrats on being in the list of Top Indian Blogs of this year :-)

Ajay Surya said...

nice article !

Anderson said...

Thanks for this great article!!!

Andy Juliadi said...

you don't put php mysql transaction in your sql transaction process?? script in file "message_like_ajax.php"..

satish chandra said...

great

Power cords said...

Great article man and most good and nice thing is you share a code with us

Mazda Arrizaqu said...

thanks bro.. it's cool.. :D

Anonymous said...

very nice tutorial...thanks

Alexander said...

Very nice! Thx!!

Harry Saggu said...

This was amazing..... Never seen before
I am big fan of you Srinivas.

Anonymous said...

You could have achieved this with less code and more security.

Magnus Eriksson said...

Wow. So many bad practices in this post.
* Firstly, like others have pointed out, mysql_* is deprecated... always use mysqli class, or better yet, pdo instead.
* Secondly, why have "like_count" in the message table when you have a like table? Do a subquery from the like table instead. That way there's no risk of unsynced tables and you can remove 1 query on like/unlike.
* Thirdly, passwords as md5? Big no no... md5 is NOT secure enough for password encryption. Use sha256 or similar. Or go a big further and have a general application salt and a unique user salt, but sure. That might be outside the scope of the article. But never tell people to use md5.

...these are just the biggest bad practices I noticed...

Anonymous said...

how to know who are all friends of mine

Jeet said...

nyc article

Anonymous said...

Magnus Eriksson,
I agree with all your points but second - if you want to get 100 posts with like count for each, you'd have 100 subqueries. At that point I believe "caching" the count in a column is a better practice (used in many CMS' out there). If your like_count gets unsynced with actual like count, then you are doing something wrong.

Anonymous said...

*Just adding to previous comment*
As for "You can remove 1 query on (un)like" point - displaying like count will always be performed way more often than liking/disliking.

Anand Roshan said...

Hi Srini Thanks man for the wonderful tutorial.
I've bookmarked your site. THank yo.. :)

Shahid said...

Nice reverse Engineering Stuff.

Alok krishali said...

Thanx for such information sir..great

Sumit Deshinge said...

superb bro......just awesome article

lukman hidayatulloh said...

cool,this is what i need, for my essay

Kumar Sonu said...

Thanks bro..

Anonymous said...

good work

Extra Creative said...

great!

What php script can I use to let the individual user view all the messages they've liked?

Ummar said...

great article.. Thanks a lot..

Anonymous said...

Great work, but mysql_connet should be mysqli_connect

Anonymous said...

in the javascript code missing closing tags });

Anonymous said...

good

Bipasha said...

I appreciate your blog post, beautifully expressed and well written.

anjaneya reddy Ch said...

nice

Anonymous said...

nice

Anonymous said...

nice

Ramaraj Ganesh said...

nice

Jubjang Jubjub said...

Thank you

Anonymous said...

gracias

kalyan said...

how can it be made realtime like the update is happenning in my browser only....how does it not show in other user who has logged in and he is not getting realtime update only its my browser showing that .how to make this update realtime in all the users browsers who are currently linked with the post

Yogita said...

Well, you posted well but though i am not much technical in handling such codes, it would be great if you can share the procedure video of above listed steps.

Anonymous said...

where are the post fields of the isset method in the message ajax.php being found from ?am using this code in aproject pliz help

Suhel Sayyad said...

Simply gr8 bro

Alex Edward said...

This really is seriously a terrific experience to me; I been to your website though researching one thing in Yahoo and google and today right after reading through your content I believe it’s a satisfaction to become in this article on your own blog. The way you define as much as possible along with the vocabularies you have genuinely nailed that. I'm also going to present my personal running a blog expertise by means of publishing my own very first website with few of days to weeks, and the writers like you'll definitely help me personally away for this job. I'm legally a regular visitor considering that at this point.

Jimmy Wilson from Aiden Pearce Leather Coat

Anonymous said...

Gracias por compartir tus conocimientos. Saludos desde Ecuador. I'm from Ecuador.

Ajay Chaurasia said...

First of all Great work Srinivas...hats off

I have some doubt with above code

After scrolling down when I click like, It again redirect me to top of the page
I think its due to href="#"... How to get out of this problem..

Thank you in Advance....!!!!!

Lesatkan said...

Oh great work, thank you this script work for me

Mohammad Wali said...

Ajay Chaurasia : Just use event.preventDefault(); to stop the default event! :)

Anonymous said...

Wow.great tut

Anonymous said...

nice.

om Ruri said...

thanks

Post a Comment