Skip to Content
PHPCODE
Like and Dislike System with jQuery, PHP and MySQL
php code / September 8, 2018

Only 10 Step Created…
Step By Step

Step 1 : Created Database. Database name :- php_code
Step 2 : Created Table Name SQL Query There Two Table Created.

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

ALTER TABLE `posts`
  ADD PRIMARY KEY (`post_id`);
ALTER TABLE `posts`
  MODIFY `post_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
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` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `post_votes`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `post_votes`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;
Step 3: Insert Query There are two table insert.
INSERT INTO `post_votes` (`id`, `post_id`, `user_id`, `vote`, `date`) VALUES
(1, 1, 123456, 1, ‘2018-09-04 00:00:00’),
(2, 2, 123456, 0, NULL),
(3, 3, 123456, 1, NULL);
INSERT INTO `posts` (`post_id`, `user_id`, `message`, `date`, `vote_up`, `vote_down`) VALUES
(1, 1, ‘PHP’, ‘2018-09-07 00:39:10’, 1, 0),
(2, 2, ‘PHP CODE’, ‘2018-09-19 20:39:08’, 0, 1),
(3, 1, ‘PHPCODEInfomation’, ‘2018-09-13 22:40:17’, 1, 0);
Step 4 :Created header.php File
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css”>
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css”>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js”></script>
<!– jQuery –>
Step 5 :Created footer.php File
<div class=”insert-post-ads1″ style=”margin-top:20px;”>
</div>
</div>
</body></html>
Step 6 :Created container.php File
</head>
<body class=””>
<div role=”navigation” class=”navbar navbar-default navbar-static-top”>
      <div class=”container”>
        <div class=”navbar-header”>
          <button data-target=”.navbar-collapse” data-toggle=”collapse” class=”navbar-toggle” type=”button”>
            <span class=”sr-only”>Toggle navigation</span>
            <span class=”icon-bar”></span>
            <span class=”icon-bar”></span>
            <span class=”icon-bar”></span>
          </button>
          <a href=”#” class=”navbar-brand”>PHPCODE</a>
        </div>
        <div class=”navbar-collapse collapse”>
          <ul class=”nav navbar-nav”>
            <li class=”active”><a href=”https://phpcodeinfomation.blogspot.com/p/php-script.html”>Home</a></li>
          </ul>
        </div><!–/.nav-collapse –>
      </div>
    </div>
<div class=”container” style=”min-height:500px;”>
<div class=”>
</div>
Step 7 : Created index.php file
<?php include(‘header.php’);?>
<title>phpcode : Demo Like and Dislike System with jQuery, PHP and MySQL</title>
<script src=”vote.js”></script>
<?php include(‘container.php’);?>
<style>
.post-options {
    width: 100%;
    text-align: right;
    margin-top: 0;
    padding: 1em 0;
}
.post-options a.options {
    clear: both;
    background: #eee;
    -moz-box-shadow: 0 1px 0 #fff inset,0 1px 0 rgba(0,0,0,0.2);
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    padding: 8px;
    font-size: .85em;
    text-transform: uppercase;
    margin: 0 0 0 10px;
    cursor: pointer;
}
.post-body {
margin-top:10px;
border: #cdcdcd 1px solid;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
margin-left:10px;
}
.post-content {
margin-top:10px;
}
</style>
<div class=”container”>
<h2>Like and Dislike System with jQuery, PHP and MySQL</h2>
<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’]; ?>”>&nbsp;&nbsp;<?php echo $post[‘vote_up’]; ?></span>&nbsp;&nbsp;&nbsp;
<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’]; ?>”>&nbsp;&nbsp;<?php echo $post[‘vote_down’]; ?></span>
</div>
</div>
<?php } ?>
</div>
<div style=”margin:50px 0px 0px 0px;”>
<a class=”btn btn-default read-more” style=”background:#3399ff;color:white” href=”https://phpcodeinfomation.blogspot.com/p/php-script.html” title=””>Back</a>
</div>
</div>
<?php include(‘footer.php’);?>
Step 8: Created Posts.php File
<?php
class Posts{
    private $host  = ‘localhost’;
    private $user  = ‘root’;
    private $password   = ”;
    private $database  = ‘php_code’;
    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;
}
}
}
?>
Step 9 :Created vote.php File
<?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);
}
}
?>
Step 10 :Created vote.js
$(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(“&nbsp;&nbsp;”+response.vote_up);
$(“#vote_down_count_”+response.post_id).html(“&nbsp;&nbsp;”+response.vote_down);
}
});
});
});
PHPCODE © 2023