February 12, 2024 5:03 am

How to create Like & Unlike System in PHP MySQL and jQuery

I have received many requests from my users to write an article on like and dislike with PHP and MySQL so today I am going to give a tutorial on like and unlike in PHP and MySQLi its very use full for your websites to get users review on pages on stories any many more.

like-unlike-php-mysql

Improved Version: Create Like & Unlike System in PHP MySQL and jQuery [Improved]

Database Details:
database name => phpgang
table name => like
db.sql
Database file run in your MySQL to create database and add data in table.

-- 
-- Table structure for table `like`
-- 

CREATE TABLE `like` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `status_id` int(10) NOT NULL,
  `like` int(10) NOT NULL,
  `un-like` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

db.php
Edit this file as per your database credentials.

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

index.php

Contains PHP code to update table records and show the current number in the file, in this file we used cookie to skip invalid likes and un-likes.

<?php
include('db.php');
$strSQL_Result  = mysqli_query($connection,"select `like`,`un-like` from `like` where id=1");
$row            = mysqli_fetch_array($strSQL_Result);

$like       = $row['like'];
$unlike     = $row['un-like'];
if($_POST)
{
    if(isset($_COOKIE["counter_gang"]))
    {
        echo "-1";
        exit;
    }
    setcookie("counter_gang", "liked", time()+3600*24, "/like-unlike-in-php-mysql/", ".demo.phpgang.com");
    if(mysqli_real_escape_string($connection,$_POST['op']) == 'like')
    {
        $update = "`like`=`like`+1";
    }
    if(mysqli_real_escape_string($connection,$_POST['op']) == 'un-like')
    {
        $update = "`un-like`=`un-like`+1";
    }
    mysqli_query($connection,"update `like` set $update where `id`=1");
    echo 1;
    exit;   
}
?>
<div class="grid">
<span id="status"></span><br>
<input type="button" value="<?php echo $like; ?>" class="button_like" id="linkeBtn" />
<input type="button" value="<?php echo $unlike; ?>" class="button_unlike" id="unlinkeBtn" />
</div>

Include db.php file and first run query in like to get number of like and un-like for a particular id here I have added static id you can make it for your dynamic system.

style.css

Contain styles of like and unlike buttons to make them look nicer on your UI.

.button_like {
    background-image: url(like.png);
    background-color: hsl(0, 0%, 97%);
    background-repeat: no-repeat; 
    background-position: 2px 0;
    border: none;           
    cursor: pointer;       
    height: 32px;          
    padding-left: 40px;    
    vertical-align: middle;
    color: hsl(0, 0%, 33%);
    border-color: hsl(0, 0%, 60%);
    -webkit-box-shadow: inset 0 1px 0 hsl(0, 100%, 100%),0 1px 0 hsla(0, 0%, 0%, .08);
    box-shadow: inset 0 1px 0 hsl(0, 100%, 100%),0 1px 0 hsla(0, 0%, 0%, .08);

}
.button_unlike {
    background-image: url(like.png);
    background-color: hsl(0, 0%, 97%);
    background-repeat: no-repeat; 
    background-position: 2px -31px;
    border: none;           
    cursor: pointer;       
    height: 32px;          
    padding-left: 40px;    
    vertical-align: middle;
    color: hsl(0, 0%, 33%);
    border-color: hsl(0, 0%, 60%);
    -webkit-box-shadow: inset 0 1px 0 hsl(0, 100%, 100%),0 1px 0 hsla(0, 0%, 0%, .08);
    box-shadow: inset 0 1px 0 hsl(0, 100%, 100%),0 1px 0 hsla(0, 0%, 0%, .08);

}
.grid
{
    height: 100px;
    width: 450px;
    margin: 0 auto;
    margin-top: 80px;
    text-align:middle;
}

script.js

Contain jQuery methods to handle like and unlike counts and disable and enable icons.

$(document).ready(function() {
$("#linkeBtn").removeAttr("disabled");
$("#unlinkeBtn").removeAttr("disabled");
$('#linkeBtn').click(function(e)
    {
        var val = parseInt($("#linkeBtn").val(), 10);
        $.post("index.php", {op:"like"},function(data)
        {
            if(data==1)
            {
                $("#status").html("Liked Sucessfully!!");
                val = val+1;
                $("#linkeBtn").val(val);
                $("#linkeBtn").attr("disabled", "disabled");
                $("#linkeBtn").css("background-image","url(likebw.png)");
            }
            else
            {
                $("#status").html("Already Liked!!");
            }
        })
    });
    $('#unlinkeBtn').click(function(e)
    {
        var val = parseInt($("#unlinkeBtn").val(), 10);
        $.post("index.php", {op:"un-like"},function(data)
        {
            if(data==1)
            {
                val = val+1;
                $("#unlinkeBtn").val(val);
                $("#unlinkeBtn").attr("disabled", "disabled");
                $("#unlinkeBtn").css("background-image","url(likebw.png)");
                $("#status").html("Un-liked Sucessfully!!");
            }
            else
            {
                $("#status").html("Already Un-liked!!");
            }
        })
    });            
});

In this js we have captured current like count and add one in that and update value of button val = val+1;

I hope you like this simple script to add like and un-like feature in your websites please update me with your feedback in comments below and we also provide you code to download and a demo to check it.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

29 responses to “How to create Like & Unlike System in PHP MySQL and jQuery”

  1. Innocent Prince says:

    Could you please make of this tutorial for WordPress ?

  2. Usama Ejaz says:

    Awesome, how about creating only one button (just like in facebook) and if user is not a liker, show “Like” else “Unlike” along with total likers 😉

  3. Huserman says:

    I think it’s not right way, because user may remove COOKIE and “Like” many times 🙂

  4. adarwash says:

    Hi, I have got my sort of working, when i click like it say already liked, and the counter stay the same until page is refreshed and i can click it as many time as i what, anyone got any idea why it doing this, thanks in advance

  5. Vo Thanh Toan says:

    Good, thanks!

  6. Brobi Wan Knobi says:

    Cannot download the code even if i sucessfully registered to the feed! 🙁

    BTW whats the ‘op’ in this “$_POST[‘op’]) ” ;

  7. love arman says:

    is this love??

  8. Pro PHP says:

    this code is sucks and is not secure
    whoever wrote this is a total newbs

  9. Max John says:

    I am already a suscriber but i can not download anymore: it says i am not a suscriber and when i try to subscribe it says I am a subscriber . Hence i can not download. I like your website you are doing a great Job

  10. Max John says:

    We want one that we can independently use on our website, not just a code

  11. doesn’t work fatso and doesn’t even have a submit button.

  12. UMESH SHEJOLE says:

    nice……..

  13. Thank you very much.

  14. Firdous Farooq Bhat says:

    How it will work when you are not giving POST METHOD in the html code?

  15. Meryam Hil says:

    Hello ^^”,
    First i want to thank you for th efforts. Secondly, i’m a brand new person in learning php code ! i created the whole files needed but i didn’t get any result except two blank buttons ! :/ i hope u can help me thank you in advanced

  16. Randy J. Tomlinson says:

    demo doesn’t work.

  17. asdasdasd says:

    a
    a

  18. asdasdasd says:

    asdasd

  19. asdasdasd says:

    asdasd

  20. asdasdasd says:

    ok

  21. asdasdasd says:

    okk

  22. dd says:

    dddddd

  23. dd says:

    ddddae

Leave a Reply

Your email address will not be published. Required fields are marked *