Like and Dislike System with jQuery, PHP and MySQL

Rating system (Like or Dislike) is an important feature of web application to track the users response for any section like website, posts content etc. It helps administrator to analyze the quality of website or post content to improve it. So if you’re looking for solution to implement rating system (like or dislike) then you’re at right place. In this tutorial you will learn how to implement Rating system (Like or Dislike) with jQuery, PHP and MySQL. We will cover this tutorial with live demo to display few posts with content and perform Like and Dislike.

Also, read:

As we will cover this tutorial with live example to implement rating system (like or dislike) with jQuery, PHP and MySQL, so the file structure for this example is following.

  • index.php
  • vote.js
  • vote.php
  • Poll.php

Step1: Create MySQL Table
As we will implement example to perform like and dislike functionality, so we will create MySQL database table posts to store posts records with message and vote count.

CREATE TABLE `posts` (
`post_id` double NOT NULL,
`user_id` double DEFAULT NULL,
`message` text,
`date` double DEFAULT NULL,
`vote_up` int(11) DEFAULT '0',
`vote_down` int(11) DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


We will also create MySQL database table post_votes to store user’s vote details related to post.

CREATE TABLE `post_votes` (
`id` int(11) NOT NULL,
`post_id` double DEFAULT NULL,
`user_id` double DEFAULT NULL,
`vote` tinyint(1) DEFAULT NULL,
`date` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step2: Display Records with Votes (Like and Dislike) Count
First we will display posts records with message and post like and dislike count. We will call Posts class method $posts->getPosts() to get posts records with like and dislike count.
<div class="row" id="post-list">
<?php
include ('Posts.php');
$posts = new Posts();
$postsData = $posts->getPosts();
foreach($postsData as $post) {
?>
<div class="col-sm-4 col-lg-4 col-md-4 post-body">
<div class="post-content"><?php echo $post['message']; ?></div>
<div class="post-options pull-right">
<a class="options" data-vote-type="1" id="post_vote_up_<?php echo $post['post_id']; ?>"><i class="glyphicon glyphicon-thumbs-up" data-original-title="Like this post"></i></a>
<span class="counter" id="vote_up_count_<?php echo $post['post_id']; ?>">  <?php echo $post['vote_up']; ?></span>   
<a class="options" data-vote-type="0" id="post_vote_down_<?php echo $post['post_id']; ?>"><i class="glyphicon glyphicon-thumbs-down" data-original-title="Dislike this post"></i></a>
<span class="counter" id="vote_down_count_<?php echo $post['post_id']; ?>">  <?php echo $post['vote_down']; ?></span>
</div>
</div>
<?php } ?>
</div>

Step3: Implement Post Like and Dislike
The posts vote updated when posts like or dislike button clicked. So in vote.js, we will make an Ajax request to vote.php to perform like and dislike functionality.

$(document).ready(function() {
$(".options").on("click", function(){
var post_id = $(this).attr("id");
post_id = post_id.replace(/\D/g,'');
var vote_type = $(this).data("vote-type");
$.ajax({
type : 'POST',
url : 'vote.php',
dataType:'json',
data : {post_id:post_id, vote_type:vote_type},
success : function(response){
$("#vote_up_count_"+response.post_id).html("  "+response.vote_up);
$("#vote_down_count_"+response.post_id).html("  "+response.vote_down);
}
});
});
});


Now in vote.php, we will handle vote up and vote down functionality. We will get user’s user_id to check to allow a single up or down vote to logged in user only. We will include class Posts.php and create object to call method $posts->getPostVotes() and $posts->getUserVotes() to get vote details. We will call method $posts->updatePostVote() to update votes to database.

<?php
include ('Posts.php');
$posts = new Posts();
// get logged in userid to vote
$user_id = 123456;
if($_POST['post_id'] && $user_id) {
$postVote = $posts->getPostVotes($_POST['post_id']);
$userVote = $posts->getUserVotes($user_id, $_POST['post_id']);
if($_POST['vote_type'] == 1) {
if($posts->isUserAlreadyVoted($user_id, $_POST['post_id']) && !$userVote['vote']) {
$postVote['vote_up'] += 1;
$postVote['vote_down'] -= 1;
$userVote['vote'] = 1;
} else if (!$posts->isUserAlreadyVoted($user_id, $_POST['post_id'])){
$postVote['vote_up'] += 1;
$userVote['vote'] = 1;
}
} else if($_POST['vote_type'] == 0) {
if($posts->isUserAlreadyVoted($user_id, $_POST['post_id']) && $userVote['vote']) {
$postVote['vote_up'] -= 1;
$postVote['vote_down'] += 1;
$userVote['vote'] = 0;
} else if(!$posts->isUserAlreadyVoted($user_id, $_POST['post_id'])) {
$postVote['vote_down'] += 1;
$userVote['vote'] = 0;
}
}
$postVoteData = array(
'post_id' => $_POST['post_id'],
'user_id' => $user_id,
'vote_up' => $postVote['vote_up'],
'vote_down' => $postVote['vote_down'],
'user_vote' => $userVote['vote']
);
// update post votes
$postVoted = $posts->updatePostVote($postVoteData);
if($postVoted) {
$response = array(
'vote_up' => $postVote['vote_up'],
'vote_down' => $postVote['vote_down'],
'post_id' => $_POST['post_id']
);
echo json_encode($response);
}
}
?>

Step4: Class Posts.php with Methods
Here is complete Posts.php class with methods to make connection to MySQL database and get and update votes details.

<?php
class Posts{
private $host = 'localhost';
private $user = 'root';
private $password = '';
private $database = 'phpzag_demos';
private $postTable = 'posts';
private $postVotesTable = 'post_votes';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$conn = new mysqli($this->host, $this->user, $this->password, $this->database);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
}else{
$this->dbConnect = $conn;
}
}
}
private function executeQuery($sqlQuery) {
$result = mysqli_query($this->dbConnect, $sqlQuery);
if(!$result){
die('Error in query: '. mysqli_error());
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$data[]=$row;
}
return $data;
}
public function getPosts(){
$sqlQuery = 'SELECT post_id, user_id, message, date, vote_up, vote_down FROM '.$this->postTable;
return $this->executeQuery($sqlQuery);
}
public function isUserAlreadyVoted($user_id, $post_id){
$sqlQuery = 'SELECT post_id, user_id, vote FROM '.$this->postVotesTable." WHERE user_id = '".$user_id."' AND post_id = '".$post_id."'";
$result = mysqli_query($this->dbConnect, $sqlQuery);
return mysqli_num_rows($result);
}
public function getUserVotes($user_id, $post_id){
$sqlQuery = 'SELECT post_id, user_id, vote FROM '.$this->postVotesTable." WHERE user_id = '".$user_id."' AND post_id = '".$post_id."'";
$result = mysqli_query($this->dbConnect, $sqlQuery);
return mysqli_fetch_array($result, MYSQL_ASSOC);
}
public function getPostVotes($post_id){
$sqlQuery = 'SELECT post_id, user_id, vote_up, vote_down FROM '.$this->postTable." WHERE post_id = '".$post_id."'";
$result = mysqli_query($this->dbConnect, $sqlQuery);
return mysqli_fetch_array($result, MYSQL_ASSOC);
}
public function updatePostVote($postVoteData) {
$sqlQuery = "UPDATE ".$this->postTable." SET vote_up = '".$postVoteData['vote_up']."' , vote_down = '".$postVoteData['vote_down']."' WHERE post_id = '".$postVoteData['post_id']."'";
mysqli_query($this->dbConnect, $sqlQuery);
$sqlVoteQuery = '';
if($this->isUserAlreadyVoted($postVoteData['user_id'], $postVoteData['post_id'])) {
$sqlVoteQuery = "UPDATE ".$this->postVotesTable." SET vote = '".$postVoteData['user_vote']."' WHERE post_id = '".$postVoteData['post_id']."' AND user_id = '".$postVoteData['user_id']."'";
} else {
$sqlVoteQuery = "INSERT INTO ".$this->postVotesTable." (id, post_id, user_id, vote) VALUES ('', '".$postVoteData['post_id']."', '".$postVoteData['user_id']."', '".$postVoteData['user_vote']."')";
}
if($sqlVoteQuery) {
mysqli_query($this->dbConnect, $sqlVoteQuery);
return true;
}
}
}
?>

You may also like:


You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download