like and dislike button code in php

Today, We want to share with you like and dislike button code in php.In this post we will show you How To Toggle Likes and Dislikes?, hear for like and unlike system using php and mysql database we will give you demo and example for implement.In this post, we will learn about PHP Toggle Like Dislike Rating System using jQuery Ajax with an example.

How to code like and dislike button using php, jquery, mysql?

Table 1: articles

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

Table 2: review_details

CREATE TABLE `review_details` (
  `visitor_id` int(11) NOT NULL,
  `article_id` int(11) NOT NULL,
  `review_action` varchar(30) NOT NULL,
   CONSTRAINT UC_review_details UNIQUE (visitor_id, article_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Insert articles

INSERT INTO `articles` (`id`, `text`) VALUES
(1, 'how to add calendar in html form'),
(2, 'html code to send email on button click'),
(3, 'how to get json data in php from url'),
(4, 'how to give space in html');

PHP Code For Likes & Dislikes system with PHP and MySQLi

index.php

<?php include('server.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Like and Dislike system</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="articles-wrapper">
   <?php foreach ($articles as $article): ?>
   	<div class="article">
      <?php echo $article['text']; ?>
      <div class="article-info">
	    <!-- if user likes article, style button differently -->
      	<i <?php if (userLiked($article['id'])): ?>
      		  class="fa fa-thumbs-up like-btn"
      	  <?php else: ?>
      		  class="fa fa-thumbs-o-up like-btn"
      	  <?php endif ?>
      	  data-id="<?php echo $article['id'] ?>"></i>
      	<span class="likes"><?php echo getLikes($article['id']); ?></span>
      	
      	    

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

Free Live Chat for Any Issue

server.php

<?php 
// connect to Your Live database
$conn = mysqli_connect('localhost', 'root', '[email protected]#$dfkjdkf', 'dislike_like');

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

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

// if user clicks like or dislike button
if (isset($_POST['action'])) {
  $article_id = $_POST['article_id'];
  $action = $_POST['action'];
  switch ($action) {
  	case 'like':
         $sql="INSERT INTO review_details (visitor_id, article_id, review_action) 
         	   VALUES ($visitor_id, $article_id, 'like') 
         	   ON DUPLICATE KEY UPDATE review_action='like'";
         break;
  	case 'dislike':
          $sql="INSERT INTO review_details (visitor_id, article_id, review_action) 
               VALUES ($visitor_id, $article_id, 'dislike') 
         	   ON DUPLICATE KEY UPDATE review_action='dislike'";
         break;
  	case 'unlike':
	      $sql="DELETE FROM review_details WHERE visitor_id=$visitor_id AND article_id=$article_id";
	      break;
  	case 'undislike':
      	  $sql="DELETE FROM review_details WHERE visitor_id=$visitor_id AND article_id=$article_id";
      break;
  	default:
  		break;
  }

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

// Get total number of likes for a particular article
function getLikes($id)
{
  global $conn;
  $sql = "SELECT COUNT(*) FROM review_details 
  		  WHERE article_id = $id AND review_action='like'";
  $rs = mysqli_query($conn, $sql);
  $result = mysqli_fetch_array($rs);
  return $result[0];
}

// Get total number of dislikes for a particular article
function getDislikes($id)
{
  global $conn;
  $sql = "SELECT COUNT(*) FROM review_details 
  		  WHERE article_id = $id AND review_action='dislike'";
  $rs = mysqli_query($conn, $sql);
  $result = mysqli_fetch_array($rs);
  return $result[0];
}

// Get total number of likes and dislikes for a particular article
function getRating($id)
{
  global $conn;
  $review = array();
  $likes_query = "SELECT COUNT(*) FROM review_details WHERE article_id = $id AND review_action='like'";
  $dislikes_query = "SELECT COUNT(*) FROM review_details 
		  			WHERE article_id = $id AND review_action='dislike'";
  $likes_rs = mysqli_query($conn, $likes_query);
  $dislikes_rs = mysqli_query($conn, $dislikes_query);
  $likes = mysqli_fetch_array($likes_rs);
  $dislikes = mysqli_fetch_array($dislikes_rs);
  $review = [
  	'likes' => $likes[0],
  	'dislikes' => $dislikes[0]
  ];
  return json_encode($review);
}

// Check if user already likes article or not
function userLiked($article_id)
{
  global $conn;
  global $visitor_id;
  $sql = "SELECT * FROM review_details WHERE visitor_id=$visitor_id 
  		  AND article_id=$article_id AND review_action='like'";
  $result = mysqli_query($conn, $sql);
  if (mysqli_num_rows($result) > 0) {
  	return true;
  }else{
  	return false;
  }
}

// Check if user already dislikes article or not
function userDisliked($article_id)
{
  global $conn;
  global $visitor_id;
  $sql = "SELECT * FROM review_details WHERE visitor_id=$visitor_id 
  		  AND article_id=$article_id AND review_action='dislike'";
  $result = mysqli_query($conn, $sql);
  if (mysqli_num_rows($result) > 0) {
  	return true;
  }else{
  	return false;
  }
}

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

main.css

.articles-wrapper {
  width: 50%;
  margin: 20px auto;
  border: 1px solid #eee;
}
.article {
  width: 90%;
  margin: 20px auto;
  padding: 10px 5px 0px 5px;
  border: 1px solid green;
}
.article-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: blue;
}

scripts.js

$(document).ready(function(){

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

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

});

// if the user clicks on the dislike button ...
$('.dislike-btn').on('click', function(){
  var article_id = $(this).data('id');
  $clicked_btn = $(this);
  if ($clicked_btn.hasClass('fa-thumbs-o-down')) {
  	action = 'dislike';
  } else if($clicked_btn.hasClass('fa-thumbs-down')){
  	action = 'undislike';
  }
  $.ajax({
  	url: 'index.php',
  	type: 'article',
  	data: {
  		'action': action,
  		'article_id': article_id
  	},
  	success: function(data){
  		res = JSON.parse(data);
  		if (action == "dislike") {
  			$clicked_btn.removeClass('fa-thumbs-o-down');
  			$clicked_btn.addClass('fa-thumbs-down');
  		} else if(action == "undislike") {
  			$clicked_btn.removeClass('fa-thumbs-down');
  			$clicked_btn.addClass('fa-thumbs-o-down');
  		}
  		// display the number of likes and dislikes
  		$clicked_btn.siblings('span.likes').text(res.likes);
  		$clicked_btn.siblings('span.dislikes').text(res.dislikes);
  		
  		// change button styling of the other button if user is reacting the second time to article
  		$clicked_btn.siblings('i.fa-thumbs-up').removeClass('fa-thumbs-up').addClass('fa-thumbs-o-up');
  	}
  });	

});

});

I hope you get an idea about Toggle Button In Php.
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.