Like Dislike Voting System using PHP , Mysql , Jquery , Ajax call , PDO

Hello , friends just some day back I have implemented survey system in one our web project . So, I think why not create a tutorial like that which help to get the rough idea of how to create the voting or like , dislike system . Now it is implemented in most of the websites like in a newspaper. For example, Who will win in today match ?
a) India b) West Indies.
These website using the same concept to build the survey . In this
tutorial, one user can vote multiple time. We can add this feature also that one user can able to vote only once , this feature I will add in future in a new tutorial :) .

For implementing the voting system we have used PHP , AJAX call , PDO database connection. We have used OOPS concept to implement it. So that we can make habit it to use always it will solve our problem in a long way.

PHP, OOPS , AJAX, PDO, voting, like, dislike

Voting System Like Dislike

We have divided it into steps for implementing the script.

1) Table Query (Database)

CREATE TABLE `blog_like_dislike` 
            (  `id` int(11) NOT NULL AUTO_INCREMENT,  
                `no_of_like` int(11) NOT NULL,  
                `no_of_dislike` int(11) NOT NULL,  
                `question_details` text NOT NULL,  
                `question_image` varchar(250) NOT NULL,  
                `question_status` tinyint(4) NOT NULL COMMENT '1 = active question , 0 : deactivate',  
                `question_title` text NOT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1

2) Database Connection file

In this we have simply created the databse connection using PHP PDO connection.Function for establishing the database connection by giving the database connection attributes . For using it change your connection parameter.

<?php

/**
 * @author Abhay Pandey (abhayhk29@gmail.com)
 * Date : 23 July 2016
 * Config class containing the database connectivity
 */

class DBConnection{
    
    //Please specify your own database credentials
    
    private $host = "localhost";
    private $db_name = "blog";
    private $user_name = "root";
    private $password = "";
    public $connection = null;
    
    public function getConnectData(){
        $this->connection = null;
        try {
            $this->connection = new PDO("mysql:host=". $this->host . ";dbname=".$this->db_name, $this->user_name, $this->password);
        } catch (Exception $exc) {
            echo "connection error please check your credentials ". $exc->getTraceAsString();
        } 

        return $this->connection;
    }
    
    public static function disconnection(){
        self::$connection = null;
    } 
}


3) Class file for fetching the data from database

For displaying the result of like and dislike and incrementing the number of votes. I have added the comments with the function for further details.

<?php

/**
 * @author Abhay Pandey <abhayhk29@gmail.com>
 * Date : 14 MAy 2016
 */

class LikeDislike{
    
    // DataBase connection Name and table NAme
    private $conn;
    private $tableLikeDislike = 'blog_like_dislike';
    
    //table data objects 
    
    public $name;

    public function __construct($db) {
        $this->conn = $db;
    }

    /**
     * return the Question details
     * @return array
     */
    public function readQuestionDetails(){
        $query = "select * from " . $this->tableLikeDislike . " ORDER BY id";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        $row = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $row[0];
    }
    
    /**
     * It will display the no of the like.
     * @param int $likeNO
     * @param int $id
     * @return No of like votes
     */
    public function updateLikeNumber($likeNO,$id){
        $like = $likeNO + 1;
        $query = "update " . $this->tableLikeDislike . " SET 
                  no_of_like = ?
                  where id = ? ";
        $stmt = $this->conn->prepare($query);
        
        $stmt->bindParam(1, $like);
        $stmt->bindParam(2, $id);

        if ($stmt->execute()) {
            return $like;
        } else {
            return false; 
        }
                
    }
    
    /**
     * It will display the no of the dislike votes and update when user will vote
     * @param int $disLikeNO
     * @param int $id
     * @return the number of the dislike
     */
    public function updateDisLikeNumber($disLikeNO,$id){
        $dislike = $disLikeNO + 1;
        $query = "update " . $this->tableLikeDislike . " SET 
                  no_of_dislike = ?
                  where id = ? ";
        $stmt = $this->conn->prepare($query);
        
        $stmt->bindParam(1, $dislike);
        $stmt->bindParam(2, $id);

        if ($stmt->execute()) {
            return $dislike;
        } else {
            return false; 
        }
                
    }
    
}

4)

Ajax file(Voting Sysytem)

In this file, we are getting the call from ajax and calling the call from LikeDislike class after manipulation of data . This file is acting as the Controller and the other class LikeDislike is acting as the Model and the index file is acting as the view . Combining all these file MVC pattern.

<?php

/**
 * @author Abhay <abhayhk29@gmail.com>
 * @copyright (c) 2016, Abhay Pandey
 * @version 1.0
 */

    if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if 
      $action = isset($_POST["action"]) ? $_POST["action"] : '';
        
      include 'includes/config.php';
      include 'includes/likedislike.php';
      
      $dataBaceConnection = new DBConnection();
      $db = $dataBaceConnection->getConnectData();
      $likeDislike = new LikeDislike($db);
      
                    $id = isset($_POST['id']) ? $_POST['id'] : '';
        switch ($action) {
            case 'like':
                    $like = isset($_POST['like']) ? $_POST['like'] : '';
                    $likeCount = $likeDislike->updateLikeNumber($like,$id);
                    $return['json'] = json_encode($likeCount);
                    echo json_encode($return);                    
                    exit();
               break;
            case 'dislike';
                    $dislike = isset($_POST['dislike']) ? $_POST['dislike'] : '';
                    $disLikeCount = $likeDislike->updateDisLikeNumber($dislike,$id);
                    $return['json'] = json_encode($disLikeCount);
                    echo json_encode($return);                    
                    exit();
                break;;

            default:
                break;
        }
    }

4) Index file

This file, contain the html of the page . The view part.

<!DOCTYPE html>
<!--
@author Abhay Kumar Pandey
email: abhayhk29@gmail.com
Date : 22 July 2016 9:45 Pm 
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title>PHP Like Dislike Tutorial Ajax Call</title>
        
            <meta charset="utf-8">
    <script src="js/jquery.min.js"></script>
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
    <script src="js/bootstrap.min.js"></script>
    <script src="js/main.js"></script>
    </head>
    <?php 
      include 'includes/config.php';
      include 'includes/likedislike.php';
      
      $dataBaceConnection = new DBConnection();
      $db = $dataBaceConnection->getConnectData();
      $likeDislike = new LikeDislike($db);
      $questionDetails = $likeDislike->readQuestionDetails();
    ?>
    <body>
        <div class="container">
            <div class="row">
                <h3>Like and Dislike Button using OOPS PHP PDO Bootstrap</h3>
                
                    <div class="panel panel-primary col-md-5">
                        <div class="panel-heading"><?php echo $questionDetails['question_title']; ?></div>
                        <div class="panel-body">
                            <div class="row">
                                <p><?php echo $questionDetails['question_details'] ?></p>
                                <img src="image/lifeatdesk.jpg" style="float: right;width: 200px;">
                            </div>
                            <div id="demo">
                                <button class="btn like btn-danger" onclick="like('<?php echo $questionDetails['id']; ?>');"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> Like <span class="likes"><?php echo $questionDetails['no_of_like']; ?></span></button>
                                <button class="btn dislike btn-warning" onclick="dislike('<?php echo $questionDetails['id']; ?>')"><span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span> Dislike <span class="dislikes"><?php echo $questionDetails['no_of_dislike']; ?></span></button>
                            </div>
                        </div>
                    </div>
                
            </div>
        </div>
    </body>
</html>

6) JavaScript File

I have created the javascript separately because this will keep clean code and easy to understand . You can see in the script I have written two functions 1) like 2) dislike
In the first function, we are increment the number of like votes . Similarly in second function, we are incrementing the number of dislike votes by using the jquery operation . Please see the code for more information.

/**
 * @author Abhay Kumar Pandey
 * @email abhayhk29@gmail.com
 */

function like(id){
    var like = $('.likes').text();
    var data = {
        "action": "like",
        "like": like,
        "id": id,
    };
    $.ajax({
            type: "POST",
            dataType: "json",
            url: "ajax.php", 
            data: data,
            success: function(data) {
                var like = $.parseJSON(data.json);
                if(like > 0){
                    $('.likes').text(like);
                }else{
                    alert('some thing wrong please try again');
                }
            }
    });
}
function dislike(id){
    var dislike = $('.dislikes').text();
    var data = {
        "action": "dislike",
        "dislike": dislike,
        "id": id,
    };
    $.ajax({
            type: "POST",
            dataType: "json",
            url: "ajax.php", 
            data: data,
            success: function(data) {
                var disLike = $.parseJSON(data.json);
                if(disLike > 0){
                    $('.dislikes').text(disLike);
                }else{
                    alert('some thing wrong please try again');
                }
            }
    });
}


s

Hope you have all like the tutorial . If you need the code please comment your email id. I will mail you the working code with sql file. Thanks foe reading the tutorial . Please share it if you like the tutorial.

30

18 Responses

  1. em
    September 21, 2016
    • Abhay Pandey
      October 6, 2016
  2. Lyndon
    March 8, 2017
  3. LUIN
    April 10, 2017
    • Abhay Pandey
      May 6, 2017
    • Demola
      January 17, 2018
  4. bruno marreiros
    June 13, 2017
    • Abhay Pandey
      June 16, 2017
  5. microchipmatt
    July 2, 2017
    • Abhay Pandey
      July 8, 2017
  6. Nico
    July 25, 2017
  7. Nico
    July 26, 2017
  8. Rakesh
    August 16, 2017
  9. venmathi
    October 4, 2017
  10. hamada
    December 6, 2017

Write a response