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.
Download Script Live Demo
Database Design
To build the message like system, you have to create three tables such as Users, Messages and message_like. 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
);
`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.
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)
);
`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)
);
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)
);
`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)
);
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>
<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 ?>">
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>';
} ?>
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").on('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/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('.like').on("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'];
}
}
}
?>
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>
<?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 } ?>
$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
$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);
?>
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);
?>
This is fantastic man, thank u...
ReplyDeleteGood
Deletenice post dude.You're genius
ReplyDeleteWell, don't you think mysql_ functions are deprecated ?
ReplyDeleteI 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.
ReplyDeleteThanks before hand!
Plz do a pdo tutorial.
ReplyDeletemany thanks
ReplyDeleteTalha Akbar: well, you can use PDO's if mysql_ functions are troubling you...
ReplyDeleteNice tutorial .. ! Thanks Srinivas !
ReplyDeleteawsm post....
ReplyDeletemysql_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
ReplyDeletenice post by the way :)
ReplyDeleteThanks dear brother ! !
ReplyDeleteReally good one..
Deleteso nice
ReplyDeleteSimply superb.......
ReplyDeleteMD5? Seriously?
ReplyDeletedude,...thanks for the post!!
ReplyDeletewow
ReplyDeleteExcellent. Initilly had issues with jquery but sorted it. Thanks a lot
ReplyDeleteThis information is great for PHP project.
ReplyDeleteHmm.. wonderfull !
ReplyDeleteThanks for your tutorial , i wanna try it !
Can this be termed as a competition for FB?
ReplyDeleteCongrats on being in the list of Top Indian Blogs of this year :-)
nice article !
ReplyDeleteThanks for this great article!!!
ReplyDeleteyou don't put php mysql transaction in your sql transaction process?? script in file "message_like_ajax.php"..
ReplyDeletegreat
ReplyDeleteGreat article man and most good and nice thing is you share a code with us
ReplyDeletethanks bro.. it's cool.. :D
ReplyDeletevery nice tutorial...thanks
ReplyDeleteVery nice! Thx!!
ReplyDeleteThis was amazing..... Never seen before
ReplyDeleteI am big fan of you Srinivas.
You could have achieved this with less code and more security.
ReplyDeleteWow. So many bad practices in this post.
ReplyDelete* 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...
Can you please send the corrected scripts by email.
DeleteThanks
how to know who are all friends of mine
ReplyDeletenyc article
ReplyDeleteMagnus Eriksson,
ReplyDeleteI 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.
*Just adding to previous comment*
ReplyDeleteAs for "You can remove 1 query on (un)like" point - displaying like count will always be performed way more often than liking/disliking.
Hi Srini Thanks man for the wonderful tutorial.
ReplyDeleteI've bookmarked your site. THank yo.. :)
Nice reverse Engineering Stuff.
ReplyDeleteThanx for such information sir..great
ReplyDeletesuperb bro......just awesome article
ReplyDeletecool,this is what i need, for my essay
ReplyDeleteThanks bro..
ReplyDeletegood work
ReplyDeletegreat!
ReplyDeleteWhat php script can I use to let the individual user view all the messages they've liked?
great article.. Thanks a lot..
ReplyDeleteGreat work, but mysql_connet should be mysqli_connect
ReplyDeletein the javascript code missing closing tags });
ReplyDeletegood
ReplyDeleteI appreciate your blog post, beautifully expressed and well written.
ReplyDeletenice
ReplyDeletenice
ReplyDeletenice
ReplyDeleteThank you
ReplyDeletegracias
ReplyDeletehow 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
ReplyDeleteWell, 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.
ReplyDeletewhere are the post fields of the isset method in the message ajax.php being found from ?am using this code in aproject pliz help
ReplyDeleteSimply gr8 bro
ReplyDeleteGracias por compartir tus conocimientos. Saludos desde Ecuador. I'm from Ecuador.
ReplyDeleteFirst of all Great work Srinivas...hats off
ReplyDeleteI 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....!!!!!
Oh great work, thank you this script work for me
ReplyDeleteAjay Chaurasia : Just use event.preventDefault(); to stop the default event! :)
ReplyDeleteWow.great tut
ReplyDeletenice.
ReplyDeletethanks
ReplyDeletegood tutorial . I started thinking to learn more about PHP , JQUERY AND MYSQL
ReplyDeletecan you please help me with the same but with java instead of php???
ReplyDeletePlease could you upload the full code files. Or tell me how many files there should be in total.
ReplyDelete(-db.php,
-message_like_ajax.php
-likes_dislikes.php)
Many thanks.
Hi could you please explain how to handle photos? would go to "uploads" field=?
ReplyDeleteThat's right, maybe u can upload some code for learning.
ReplyDeleteFOREIGN KEY (uid_fk) REFERENCES users(uid),
ReplyDeleteFOREIGN KEY (msg_id_fk) REFERENCES messages(msg_id)
this is a problem when i creating a table in my sql
Hi this is very help full keep you the good work
ReplyDeletethanks brother
ReplyDeletePlease upload full files
ReplyDeletegood, thanks
ReplyDeletethanks
ReplyDeleteWhat is this $like_count. I cannot find it....where is this value from?
ReplyDeleteis there any solution ??? of $like_count variable
DeleteUndefined variable: like_count in...
ReplyDelete