Facebook Like System with Jquery, MySQL and PHP.
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 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
);

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").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'];
}
}
}
?>

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);
?>
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


83 comments:

  1. This is fantastic man, thank u...

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

    ReplyDelete
  3. 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!

    ReplyDelete
  4. Plz do a pdo tutorial.

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

    ReplyDelete
  6. 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

    ReplyDelete
  7. MD5? Seriously?

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

    ReplyDelete
  9. This information is great for PHP project.

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

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

    ReplyDelete
  12. Thanks for this great article!!!

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

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

    ReplyDelete
  15. very nice tutorial...thanks

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

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

    ReplyDelete
  18. 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...

    ReplyDelete
    Replies
    1. Can you please send the corrected scripts by email.
      Thanks

      Delete
  19. how to know who are all friends of mine

    ReplyDelete
  20. 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.

    ReplyDelete
  21. *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.

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

    ReplyDelete
  23. Nice reverse Engineering Stuff.

    ReplyDelete
  24. Thanx for such information sir..great

    ReplyDelete
  25. superb bro......just awesome article

    ReplyDelete
  26. cool,this is what i need, for my essay

    ReplyDelete
  27. great!

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

    ReplyDelete
  28. great article.. Thanks a lot..

    ReplyDelete
  29. Great work, but mysql_connet should be mysqli_connect

    ReplyDelete
  30. in the javascript code missing closing tags });

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

    ReplyDelete
  32. 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

    ReplyDelete
  33. 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.

    ReplyDelete
  34. 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

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

    ReplyDelete
  36. 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....!!!!!

    ReplyDelete
  37. Oh great work, thank you this script work for me

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

    ReplyDelete
  39. good tutorial . I started thinking to learn more about PHP , JQUERY AND MYSQL

    ReplyDelete
  40. can you please help me with the same but with java instead of php???

    ReplyDelete
  41. Please could you upload the full code files. Or tell me how many files there should be in total.
    (-db.php,
    -message_like_ajax.php
    -likes_dislikes.php)
    Many thanks.

    ReplyDelete
  42. Hi could you please explain how to handle photos? would go to "uploads" field=?

    ReplyDelete
  43. That's right, maybe u can upload some code for learning.

    ReplyDelete
  44. FOREIGN KEY (uid_fk) REFERENCES users(uid),
    FOREIGN KEY (msg_id_fk) REFERENCES messages(msg_id)

    this is a problem when i creating a table in my sql

    ReplyDelete
  45. Hi this is very help full keep you the good work

    ReplyDelete
  46. What is this $like_count. I cannot find it....where is this value from?

    ReplyDelete
  47. Undefined variable: like_count in...

    ReplyDelete

Make in India