5 Steps Simple Like Dislike System In PHP MySQL

Welcome to a tutorial on how to build a simple like and dislike rating system with PHP and MySQL. Social media is big these days and I am sure you have already seen “upvote”, “downvote”, “like”, and “dislike” features everywhere on Facebook, YouTube, Twitter, and more. Well, if you want to create your own independent like/dislikes system, it really isn’t that difficult.

A basic like/dislike system only requires a couple of key components:

  1. A database table to store the user’s likes and dislikes.
  2. A PHP library and AJAX handler to manage the likes and dislikes.
  3. Lastly, implementation onto the pages themselves.

Let us walk through an actual example in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Like Dislike Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

  • Create a database and import the 1-database.sql file.
  • Change the database settings in 2-reactions.php to your own.
  • Launch 4a-demo.html in your browser. Use http://, not file://.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

LIKE DISLIKE SYSTEM

All right, let us now get into the details of building a like dislike system with PHP and MYSQL.

 

STEP 1) REACTIONS DATABASE TABLE

1-database.sql
CREATE TABLE `reactions` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `reaction` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `reactions`
  ADD PRIMARY KEY (`id`,`user_id`),
  ADD KEY `reaction` (`reaction`);
Field Description
id Primary and foreign key. The post ID, product ID, video ID – Whatever you want to add a like/dislike button to.
user_id Primary and foreign key. The user who liked/disliked.
reaction For this example, we will use -1 for dislike and 1 for like.

Yep, 3 fields are actually all we need to record the likes and dislikes.

 

 

STEP 2) PHP REACTIONS LIBRARY

2-reactions.php
<?php
class Reactions {
  // (A) CONSTRUCTOR - CONNECT TO DATABASE
  private $pdo;
  private $stmt;
  public $error;
  function __construct () {
    try {
      $this->pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
        DB_USER, DB_PASSWORD, [
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED
        ]
      );
    } catch (Exception $ex) { exit($ex->getMessage()); }
  }

  // (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
  function __destruct () {
    $this->pdo = null;
    $this->stmt = null;
  }

  // (C) GET REACTIONS FOR ID
  function get ($id, $uid=null) {
    // (C1) GET TOTAL REACTIONS
    $results = ["react"=>[]];
    $this->stmt = $this->pdo->prepare(
      "SELECT `reaction`, COUNT(`reaction`) `total`
      FROM `reactions` WHERE `id`=?
      GROUP BY `reaction`"
    );
    $this->stmt->execute([$id]);
    while ($row = $this->stmt->fetch()) {
      $results["react"][$row["reaction"]] = $row["total"];
    }

    // (C2) GET REACTION BY USER (IF SPECIFIED)
    if ($uid !== null) {
      $this->stmt = $this->pdo->prepare(
        "SELECT `reaction` FROM `reactions` WHERE `id`=? AND `user_id`=?"
      );
      $this->stmt->execute([$id, $uid]);
      $results["user"] = $this->stmt->fetchColumn();
    }
    return $results;
  }
 
  // (D) SAVE REACTION
  function save ($id, $uid, $react) {
    // (D1) FORMULATE SQL
    if ($react == 0) {
      $sql = "DELETE FROM `reactions` WHERE `id`=? AND `user_id`=?";
      $data = [$id, $uid];
    } else {
      $sql = "REPLACE INTO `reactions` (`id`, `user_id`, `reaction`) VALUES (?,?,?)";
      $data = [$id, $uid, $react];
    }
 
    // (D2) EXECUTE SQL
    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($data);
      return true;
    } catch (Exception $ex) {
      $this->error = $ex->getMessage();
      return false;
    }
  }
}

// (E) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8");
define("DB_USER", "root");
define("DB_PASSWORD", "");

// (F) CREATE NEW CONTENT OBJECT
$REACT = new Reactions();

This one looks massive at first, but keep calm and look carefully.

  • A & B – On creating a $REACT = new Reactions() object, the constructor will automatically connect to the database. The destructor will close the connection when done.
  • C – function get() This one gets the total number of reactions (likes and dislikes) for the given ID. If the user ID is provided, it will also get the user’s reaction.
  • D – function save() Self-explanatory, save a user reaction. Set $react = 0 to remove the user’s reaction.
  • E & F – The database settings, and creating a new Reactions() object. Doh.

 

 

STEP 3) REACTIONS AJAX HANDLER

3-ajax.php
<?php
// (A) INIT
require "2-reactions.php";
$userID = 1; // For demo only, use $_SESSION in your own project.

// (B) SAVE/UPDATE REACTION
if (isset($_POST["react"])) {
  if (!$REACT->save($_POST["id"], $userID, $_POST["react"])) {
    exit(json_encode(["error" => $REACT->error]));
  }
}

// (C) GET REACTIONS
$result = $REACT->get($_POST["id"], $userID);
if (isset($_POST["react"])) { $result["save"] = 1; }

// (D) RESPONSE
/*
$result = [
  "error" => "ERROR MESSAGE",
  "save" => 1 (IF UPDATE REACTION OK),
  "react" => [1 => NUMBER OF LIKES, -1 => NUMBER OF DISLIKES],
  "user" => 1 OR -1 OR NONE
];
*/
echo json_encode($result);

This is a simple AJAX handler to get and save the likes/dislikes. How it works:

  • Just send $_POST["id"]=N to this script to get the number of likes and dislikes.
  • To update the user’s reaction, also send $_POST["react"] = -1 OR 0 OR 1.

 

 

STEP 4) DUMMY PRODUCT PAGE

4a-demo.html
<?php
<!-- (A) LOAD CSS + JS -->
<link rel="stylesheet" href="likedis.css"/>
<script src="likedis.js"></script>
<script src="4b-demo.js"></script>

<!-- (B) HTML TO RENDER LIKE/DISLIKE BUTTON -->
<div id="demowrap">
  <input type="hidden" id="product-id" value="900"/>
  <img src="raspberry.jpg"/>
  <div id="demo"></div>
</div>

Well, a dummy product page. The important parts are:

  • <input type="hidden" id="product-id" value="N"/> A hidden product ID holder.
  • <div id="demo"></div> To generate the like/dislike button.

The rest will be handled via Javascript, and the like/dislike button is a “plugin” that I created. Shall leave a link below if you are interested to learn more.

 

STEP 5) THE JAVASCRIPT

4b-demo.js
var uplike = {
  // (A) AJAX HELPER FUNCTION
  ajax : function (after, react) {
    // (A1) FORM DATA
    var data = new FormData();
    data.append("id", document.getElementById("product-id").value);
    if (react) { data.append("react", react); }
 
    // (A2) AJAX CALL
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "3-ajax.php");
    xhr.onload = after;
    xhr.send(data);
  },
 
  // (B) INITIALIZE LIKE/DISLIKE
  init : function () {
    var res = JSON.parse(this.response);
    likedis.attach({
      target : document.getElementById("demo"),
      like : res.user ? res.user : 0,
      uptxt : res.react[1] ? res.react[1] : 0,
      downtxt : res.react[-1] ? res.react[-1] : 0,
      change : uplike.change
    });
  },
 
  // (C) UPDATE LIKE STATUS
  change : function (react, button, up, down) {
    uplike.ajax(function(){
      var res = JSON.parse(this.response);
      if (res.error) { alert(res.error); }
      else {
        up.innerHTML = res.react[1] ? res.react[1] : 0;
        down.innerHTML = res.react[-1] ? res.react[-1] : 0;
      }
    }, react);
  }
};
 
// (D) INITIALIZE
window.addEventListener("DOMContentLoaded", function () {
  uplike.ajax(uplike.init);
});

This looks massive again, but keep calm and look carefully.

  1. ajax() is a helper function that does an AJAX call to 3-ajax.php.
  2. init() is called on page load, to attach the like/dislike button.
  3. change() is called whenever the user clicks on like/dislike. Does an AJAX call to 3-ajaax.php to update and get the latest like/dislike count.

Yep. That’s all.

 

 

USEFUL BITS & LINKS

That’s all for the code, and here are a few small extras that may be useful to you.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to improve your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

6 thoughts on “5 Steps Simple Like Dislike System In PHP MySQL”

      1. No problems here with Chrome, Opera, Edge, and Firefox – Not sure which version of Firefox you are using… Your customizations probably broke it.

Leave a Comment

Your email address will not be published. Required fields are marked *