November 3, 2016 9:55 am

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

We have created a like and unlike script on our readers request we received many users feedback they face problems in counter etc. Now I have fixed all bugs and created its improved version with multiple like unlike on single page and for products and improve some JavaScript and CSS so I hope you like it.

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

[wpdm_file id=182]DEMO

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

-- 
-- Table structure for table `likes`
-- 

CREATE TABLE `likes` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `pid` int(10) NOT NULL,
  `like` int(10) NOT NULL,
  `unlike` int(10) NOT NULL,
  `uid` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1;



-- --------------------------------------------------------

-- 
-- Table structure for table `products`
-- 

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_name` varchar(255) NOT NULL,
  `price` double(10,2) NOT NULL DEFAULT '0.00',
  `image` varchar(255) NOT NULL,
  `status` int(2) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4;

-- 
-- Dumping data for table `products`
-- 

INSERT INTO `products` VALUES (1, 'PHP Books', 20.00, '1.jpg', 1);
INSERT INTO `products` VALUES (2, 'RestAPI Code', 10.00, '2.jpg', 1);
INSERT INTO `products` VALUES (3, 'PHPGang Annual Subscription', 100.00, '3.jpg', 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.

Main file show products list and and like buttons:

<?php
session_start();
include("db.php");
if(!isset($_SESSION['user']))
{
    $_SESSION['user'] = session_id();
}
$uid = $_SESSION['user'];  // set your user id settings

$query  = "SELECT * FROM  `products`"; // products list
$res    = mysqli_query($connection,$query);
$HTML = "";
while($row=mysqli_fetch_array($res))
{
    // get likes and dislikes of a product
    $query = mysqli_query($connection,"select sum(`like`) as `like`,sum(`unlike`) as `unlike` from `likes` where pid = ".$row['id']);
    $rowCount = mysqli_fetch_array($query);
    if($rowCount['like'] == "")
        $rowCount['like'] = 0;
        
    if($rowCount['unlike'] == "")
        $rowCount['unlike'] = 0;
        
    if($uid == "") // if user not loggedin then show login link on like button click
    {
        $like = '
            <input onclick="location.href = \'login.php\';" type="button" value="'.$rowCount['like'].'" rel="'.$row['id'].'" data-toggle="tooltip"  data-placement="top" title="Login to Like" class="button_like" />
            <input onclick="location.href = \'login.php\';" type="button" value="'.$rowCount['unlike'].'" rel="'.$row['id'].'" data-toggle="tooltip" data-placement="top" title="Login to Unlike" class="button_unlike" />';
    }
    else
    {
        $query = mysqli_query($connection,"SELECT * from `likes` WHERE pid='".$row['id']."' and uid='".$uid."'");
        if(mysqli_num_rows($query)>0){ //if already liked od disliked a product
            $likeORunlike = mysqli_fetch_array($query);
            // clear values of variables
            $liked = '';
            $unliked = '';
            $disable_like = '';
            $disable_unlike = '';
            
            if($likeORunlike['like'] == 1) // if alredy liked then disable like button
            {
                $liked = 'disabled="disabled"';
                $disable_unlike = "button_disable";
            }
            elseif($likeORunlike['unlike'] == 1) // if alredy dislike the disable unlike button
            {
                $unliked = 'disabled="disabled"';
                $disable_like = "button_disable";
            }
            
            $like = '
            <input '.$liked.' type="button" value="'.$rowCount['like'].'" rel="'.$row['id'].'" data-toggle="tooltip"  data-placement="top" title="Like" class="button_like '.$disable_like.'" id="linkeBtn_'.$row['id'].'" />
            <input '.$unliked.' type="button" value="'.$rowCount['unlike'].'" rel="'.$row['id'].'" data-toggle="tooltip" data-placement="top" title="Un-Like" class="button_unlike '.$disable_unlike.'" id="unlinkeBtn_'.$row['id'].'" />
            ';
        }
        else{ //not liked and disliked product
            $like = '
            <input  type="button" value="'.$rowCount['like'].'" rel="'.$row['id'].'" data-toggle="tooltip"  data-placement="top" title="Like" class="button_like" id="linkeBtn_'.$row['id'].'" />
            <input  type="button" value="'.$rowCount['unlike'].'" rel="'.$row['id'].'" data-toggle="tooltip" data-placement="top" title="Un-Like" class="button_unlike" id="unlinkeBtn_'.$row['id'].'" />
            ';
        }
    }
        
    $HTML.='
        <li> <img src="images/'.$row['image'].'" class="">
            <h4 class="">'.$row['product_name'].'</h4>
            <div class="product-price">
                <span class="normal-price">$'.$row['price'].'</span>
            </div>
            <a href="#" class="btn btn-default navbar-btn" >Buy Now</a>
            <div class="grid">
                '.$like.'
            </div>
        </li>';
}

?>
<!doctype html>
<head>
    <title>Create Like & Unlike System in PHP MySQL and jQuery [Improved] | PHPGang.com</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <script type="text/javascript" src="jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="script.js"></script>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  </head>
  <body>
  <h2><a href="https://www.phpgang.com/?p=4814">Create Like & Unlike System in PHP MySQL and jQuery [Improved]</a></h2><br><br>
  <div class="container">
    <div class="row">
    <h1>PHPGang Shopping store</h1>
        <div class="col-sm-12 col-md-12">
            <ul class="thumbnail-list">
            <?php echo $HTML; ?>
            </ul>
        </div>
    </div>
</div>
  </body>
</html>

To post like button action below code used:

<?php
if($_POST)
{
    $pid    = mysqli_real_escape_string($connection,$_POST['pid']);  // product id
    $op     = mysqli_real_escape_string($connection,$_POST['op']);  // like or unlike op
    

    if($op == "like")
    {
        $gofor = "like";
    }
    elseif($op == "unlike")
    {
        $gofor = "unlike";
    }
    else
    {
        exit;
    }
    // check if alredy liked or not query
    $query = mysqli_query($connection,"SELECT * from `likes` WHERE pid='".$pid."' and uid='".$uid."'");
    $num_rows = mysqli_num_rows($query);

    if($num_rows>0) // check if alredy liked or not condition
    {
        $likeORunlike = mysqli_fetch_array($query);
    
        if($likeORunlike['like'] == 1)  // if alredy liked set unlike for alredy liked product
        {
            mysqli_query($connection,"update `likes` set `unlike`=1,`like`=0 where id='".$likeORunlike['id']."' and uid='".$uid."'");
            echo 2;
        }
        elseif($likeORunlike['unlike'] == 1) // if alredy unliked set like for alredy unliked product
        {
            mysqli_query($connection,"update `likes` set `like`=1,`unlike`=0 where id='".$likeORunlike['id']."' and uid='".$uid."'");
            echo 2;
        }
    }
    else  // New Like
    {
       mysqli_query($connection,"INSERT INTO `likes` (`pid`,`uid`, `$gofor`) VALUES ('$pid','$uid','1')");
       echo 1;
    }
    exit;
}
?>

Complete Demo code available in download area click download to download code a running demo here

This is the simple and easy code for like and unlike system I hope you guyz like this please share your feedback in comments. If you face any issue please fee free to comment below.

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:

9 responses to “Create Like & Unlike System in PHP MySQL and jQuery [Improved]”

  1. David says:

    Realy like this tutorial and 100% going to implement in my project.

  2. Bud Kaye says:

    Howdy! 🙂 Love it but I am getting an error… “PHP Notice: Undefined variable: HTML in /”
    I think the error is in the “index.php” file. Your demo works great! But I found a typo in the downloaded code:
    See image attached… 🙂 https://uploads.disquscdn.com/images/b24eb0d3ac5e24b7e8d8edfe690be8f10a8f97beee79762011af0bba5b4baad7.jpg

  3. Alexander Fleischer says:

    In which case the uid would be empty? If i delete my cookies i can vote again and again

    • Php guru says:

      If you are not logged in then uid will be empty. To vote you need to create account first.

      • Alexander Fleischer says:

        ok, i thougt it was without an login, like the demo. But in the
        script i’m always logged in. if the session var is not set you set it,
        instead redirecting to a login page

  4. Jan Jan Molendijk says:

    I tested your script succesfully thanks…

    But i wanna use this script into a notice-form with pagination
    i did not succeed it to work can you help me out ?

Leave a Reply

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