Like Dislike system with PHP and MySQL

Today, We want to share with you Like Dislike system with PHP and MySQL.In this post we will show you Like and Dislike System with jQuery, PHP and MySQL, hear for Like Dislike Rating System with jQuery, Ajax and PHP we will give you demo and example for implement.In this post, we will learn about How to create Like & Unlike System in PHP MySQL and jQuery with an example.

Like Dislike system with PHP and MySQL

There are the Following The simple About Like Dislike system with PHP and MySQL Full Information With Example and source code.

As I will cover this Post with live Working example to develop Like and Unlike system using PHP and MySQL database, so the php code for likes and dislikes for this example is following below.

Step 1:

Table 1: products

CREATE TABLE `products` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `text` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Table 2: review_5_star_rating_information

CREATE TABLE `review_5_star_rating_information` (
  `client_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `rating_type_of_data` varchar(30) NOT NULL,
   CONSTRAINT UC_review_5_star_rating_information UNIQUE (client_id, product_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 2:

INSERT MySQL Database table Data

INSERT INTO `products` (`id`, `text`) VALUES
(1, 'Welcome To the first product'),
(2, 'Welcome To the second Ipjone'),
(3, 'Welcome To the third product'),
(4, 'Welcome To the fourth Mobile');

Step : 3

index.php

<?php include('server.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Like and Dislike system - www.pakainfo.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <link rel="stylesheet" href="main.css">
</head>
<body>
  <div class="products-wrapper">
   <?php foreach ($products as $product): ?>
   	<div class="product">
      <?php echo $product['text']; ?>
      <div class="product-info">
	    <!-- if user harts product, style button differently -->
      	<i <?php if (userLiked($product['id'])): ?>
      		  class="fa fa-thumbs-up like-btn"
      	  <?php else: ?>
      		  class="fa fa-thumbs-o-up like-btn"
      	  <?php endif ?>
      	  data-id="<?php echo $product['id'] ?>"></i>
      	<span class="harts"><?php echo getLikes($product['id']); ?></span>
      	
      	    

	    <!-- if client oppose product, style button differently -->
      	<i 
      	  <?php if (userDisliked($product['id'])): ?>
      		  class="fa fa-thumbs-down unharts-btn"
      	  <?php else: ?>
      		  class="fa fa-thumbs-o-down unharts-btn"
      	  <?php endif ?>
      	  data-id="<?php echo $product['id'] ?>"></i>
      	<span class="oppose"><?php echo getDisharts($product['id']); ?></span>
      </div>
   	</div>
   <?php endforeach ?>
  </div>
  <script src="scripts.js"></script>
</body>
</html>

Step :4

main.css

.products-wrapper {
  width: 50%;
  margin: 20px auto;
  border: 1px solid #eee;
}
.product {
  width: 90%;
  margin: 20px auto;
  padding: 10px 5px 0px 5px;
  border: 1px solid green;
}
.product-info {
  margin: 10px auto 0px;
  padding: 5px;
}
.fa {
  font-size: 1.2em;
}
.fa-thumbs-down, .fa-thumbs-o-down {
  transform:rotateY(180deg);
}
.logged_in_user {
  padding: 10px 30px 0px;
}
i {
  color: yellow;
}

Step : 5

server.php:

<?php 
// connect to database
$conn = mysqli_connect('localhost', 'root', '', 'unharts_like');

// lets assume a user is logged in with id $client_id
$client_id = 2;

if (!$conn) {
  die("Error connecting to database: " . mysqli_connect_error($conn));
  exit();
}

// if user clicks like or unharts button
if (isset($_POST['type_of_data'])) {
  $product_id = $_POST['product_id'];
  $type_of_data = $_POST['type_of_data'];
  switch ($type_of_data) {
  	case 'like':
         $sql="INSERT INTO review_5_star_rating_information (client_id, product_id, rating_type_of_data) 
         	   VALUES ($client_id, $product_id, 'like') 
         	   ON DUPLICATE KEY UPDATE rating_type_of_data='like'";
         break;
  	case 'unharts':
          $sql="INSERT INTO review_5_star_rating_information (client_id, product_id, rating_type_of_data) 
               VALUES ($client_id, $product_id, 'unharts') 
         	   ON DUPLICATE KEY UPDATE rating_type_of_data='unharts'";
         break;
  	case 'unlike':
	      $sql="DELETE FROM review_5_star_rating_information WHERE client_id=$client_id AND product_id=$product_id";
	      break;
  	case 'unoppose':
      	  $sql="DELETE FROM review_5_star_rating_information WHERE client_id=$client_id AND product_id=$product_id";
      break;
  	default:
  		break;
  }

  // execute query to effect changes in the database ...
  mysqli_query($conn, $sql);
  echo getRating($product_id);
  exit(0);
}

// Get total number of harts for a particular product
function getLikes($id)
{
  global $conn;
  $sql = "SELECT COUNT(*) FROM review_5_star_rating_information 
  		  WHERE product_id = $id AND rating_type_of_data='like'";
  $rs = mysqli_query($conn, $sql);
  $result = mysqli_fetch_array($rs);
  return $result[0];
}

// Get total number of oppose for a particular product
function getDisharts($id)
{
  global $conn;
  $sql = "SELECT COUNT(*) FROM review_5_star_rating_information 
  		  WHERE product_id = $id AND rating_type_of_data='unharts'";
  $rs = mysqli_query($conn, $sql);
  $result = mysqli_fetch_array($rs);
  return $result[0];
}

// Get total number of harts and oppose for a particular product
function getRating($id)
{
  global $conn;
  $rating = array();
  $harts_query = "SELECT COUNT(*) FROM review_5_star_rating_information WHERE product_id = $id AND rating_type_of_data='like'";
  $oppose_query = "SELECT COUNT(*) FROM review_5_star_rating_information 
		  			WHERE product_id = $id AND rating_type_of_data='unharts'";
  $harts_rs = mysqli_query($conn, $harts_query);
  $oppose_rs = mysqli_query($conn, $oppose_query);
  $harts = mysqli_fetch_array($harts_rs);
  $oppose = mysqli_fetch_array($oppose_rs);
  $rating = [
  	'harts' => $harts[0],
  	'oppose' => $oppose[0]
  ];
  return json_encode($rating);
}

// Check if user already harts product or not
function userLiked($product_id)
{
  global $conn;
  global $client_id;
  $sql = "SELECT * FROM review_5_star_rating_information WHERE client_id=$client_id 
  		  AND product_id=$product_id AND rating_type_of_data='like'";
  $result = mysqli_query($conn, $sql);
  if (mysqli_num_rows($result) > 0) {
  	return true;
  }else{
  	return false;
  }
}

// Check if user already oppose product or not
function userDisliked($product_id)
{
  global $conn;
  global $client_id;
  $sql = "SELECT * FROM review_5_star_rating_information WHERE client_id=$client_id 
  		  AND product_id=$product_id AND rating_type_of_data='unharts'";
  $result = mysqli_query($conn, $sql);
  if (mysqli_num_rows($result) > 0) {
  	return true;
  }else{
  	return false;
  }
}

$sql = "SELECT * FROM products";
$result = mysqli_query($conn, $sql);
// fetch all products from database
// return them as an associative array called $products
$products = mysqli_fetch_all($result, MYSQLI_ASSOC);

Step : 6

scripts.js:

$(document).ready(function(){

// if the user clicks on the like button ...
$('.like-btn').on('click', function(){
  var product_id = $(this).data('id');
  $like_dislike_btn = $(this);
  if ($like_dislike_btn.hasClass('fa-thumbs-o-up')) {
  	type_of_data = 'like';
  } else if($like_dislike_btn.hasClass('fa-thumbs-up')){
  	type_of_data = 'unlike';
  }
  $.ajax({
  	url: 'index.php',
  	type: 'product',
  	data: {
  		'type_of_data': type_of_data,
  		'product_id': product_id
  	},
  	success: function(data){
  		res = JSON.parse(data);
  		if (type_of_data == "like") {
  			$like_dislike_btn.removeClass('fa-thumbs-o-up');
  			$like_dislike_btn.addClass('fa-thumbs-up');
  		} else if(type_of_data == "unlike") {
  			$like_dislike_btn.removeClass('fa-thumbs-up');
  			$like_dislike_btn.addClass('fa-thumbs-o-up');
  		}
  		// display the number of harts and oppose
  		$like_dislike_btn.siblings('span.harts').text(res.harts);
  		$like_dislike_btn.siblings('span.oppose').text(res.oppose);

  		// change button styling of the other button if user is reacting the second time to product
  		$like_dislike_btn.siblings('i.fa-thumbs-down').removeClass('fa-thumbs-down').addClass('fa-thumbs-o-down');
  	}
  });		

});

// if the user clicks on the unharts button ...
$('.unharts-btn').on('click', function(){
  var product_id = $(this).data('id');
  $like_dislike_btn = $(this);
  if ($like_dislike_btn.hasClass('fa-thumbs-o-down')) {
  	type_of_data = 'unharts';
  } else if($like_dislike_btn.hasClass('fa-thumbs-down')){
  	type_of_data = 'unoppose';
  }
  $.ajax({
  	url: 'index.php',
  	type: 'product',
  	data: {
  		'type_of_data': type_of_data,
  		'product_id': product_id
  	},
  	success: function(data){
  		res = JSON.parse(data);
  		if (type_of_data == "unharts") {
  			$like_dislike_btn.removeClass('fa-thumbs-o-down');
  			$like_dislike_btn.addClass('fa-thumbs-down');
  		} else if(type_of_data == "unoppose") {
  			$like_dislike_btn.removeClass('fa-thumbs-down');
  			$like_dislike_btn.addClass('fa-thumbs-o-down');
  		}
  		// display the number of harts and oppose
  		$like_dislike_btn.siblings('span.harts').text(res.harts);
  		$like_dislike_btn.siblings('span.oppose').text(res.oppose);
  		
  		// change button styling of the other button if user is reacting the second time to product
  		$like_dislike_btn.siblings('i.fa-thumbs-up').removeClass('fa-thumbs-up').addClass('fa-thumbs-o-up');
  	}
  });	

});

});

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Like Dislike system with PHP and MySQL.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Ajax Shopping Cart PHP MYSQLi Tutorial With Example
  2.   woocommerce_payment_complete Hooks
  3.   Ajax Autocomplete Live Search Suggestion using PHP MySQL
  4.   AngularJS Share data between controllers
  5.   Dynamic Autocomplete Textbox in jQuery Ajax
  6.   PHP Send Beautiful HTML Email Templates
  7.   PHP Autocomplete Input tags with Dynamic Data using jquery Ajax
  8.   jQuery Multiple Tag Input with Dynamic Autocomplete Example
  9.   Send Simple Mail Function using PHP
  10.   jquery validate CKEditor example with rules and messages