Tuesday 25 September 2018

Like dislike rating system using jQuery, Ajax, PHP and MySQL

Like dislike rating system is quite useful for any website. Through this admin as well as webmasters can understand the users likes and dislikes. In this tutorial, I made a simple like dislike rating system using jQuery, Ajax, PHP, and MySQL. No page refreshing is required because I used jQuery and Ajax. Also, we store the data into the MySQL database using PHP and MySQL.
This like dislike rating system is designed such a way that users have to log in first to the website before doing like or dislike and each user can like or dislike each post several times but only one will be counted either one like or one dislike.

Before proceeding, have a look at the file structure–
  • index.php
  • mtb.js
  • update-choice.php
  • check-session.php
  • logout.php
  • logout.php

Database Tables

Create the following two tables in the database. Download the complete source code from the below link where you will get the sample data for these two tables. Instead of creating one extra table for storing like and dislike counts, I created two extra columns (likes and dislikes) in the post_list table which will store the ids of the logged in users. And the number of ids of each column is the number of likes and dislikes respectively.
  1. CREATE TABLE `user_login` (
  2. `id` int(11) NOT NULL,
  3. `name` varchar(255) NOT NULL,
  4. `username` varchar(255) NOT NULL,
  5. `password` varchar(255) NOT NULL
  6. ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  7. CREATE TABLE `post_list` (
  8. `id` int(11) NOT NULL,
  9. `title` varchar(255) NOT NULL,
  10. `excerpt` varchar(255) NOT NULL,
  11. `image` varchar(255) NOT NULL,
  12. `link` varchar(255) NOT NULL,
  13. `likes` text NOT NULL,
  14. `dislikes` text NOT NULL
  15. ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

HTML & PHP – Display The Posts (index.php)

The below code fetches data from the database and displays the list of post.
  1. <div class="container-fluid">
  2. <div class="row">
  3. <?php
  4. $qry = "select * from `post_list`";
  5. $res = mysqli_query($con, $qry);
  6. if(mysqli_num_rows($res) > 0) {
  7. while($row = mysqli_fetch_object($res)) {
  8. $likes = array_filter(explode(',', $row->likes), function($value) { return $value !== ''; });
  9. $dislikes = array_filter(explode(',', $row->dislikes), function($value) { return $value !== ''; });
  10. ?>
  11. <div class="col-md-3">
  12. <div class="mtb-post">
  13. <form action="" method="post" id="<?php echo $row->id;?>">
  14. <input type="hidden" name="post_id" id="post_id" value="<?php echo $row->id;?>">
  15. <img class="img-fluid" src="images/<?php echo $row->image;?>">
  16. <div class="post-info">
  17. <div class="caption"><a href="<?php echo $row->link;?>" target="_blank"><h1><?php echo $row->title;?><h1></a></div>
  18. <div class="excerpt"><?php echo $row->excerpt;?></div>
  19. <div class="like-dislike">
  20. <div class="like"><div class="counter"><?php echo sizeof($likes);?></div></div>
  21. <div class="dislike"><div class="counter"><?php echo sizeof($dislikes);?></div></div>
  22. <div class="clearfix"></div>
  23. </div>
  24. </div>
  25. <div class="clearfix"></div>
  26. </form>
  27. </div>
  28. </div>
  29. <?php
  30. }
  31. }
  32. ?>
  33. </div>
  34. </div>

jQuery and Ajax – Like Dislike Rating System (mtb.js)

Simple Ajax call which sends data to the update-choice.php and in returns get the number of likes and dislikes of any particular post.
  1. $(document).ready(function() {
  2. $('.like, .dislike').click(function() {
  3. var action = $(this).attr('class');
  4. var post_id = $(this).parent().parent().parent().find("#post_id").val();
  5. $.ajax({
  6. url: 'check-session.php',
  7. method: 'post',
  8. success: function(data){
  9. if(data != '') {
  10. $.ajax({
  11. url: 'update-choice.php',
  12. method: 'post',
  13. data:{action:action, post_id:post_id},
  14. success: function(resp){
  15. resp = $.trim(resp);
  16. if(resp != '') {
  17. resp = resp.split('|');
  18. $('form#'+post_id+' .like .counter').html(resp[0]);
  19. $('form#'+post_id+' .dislike .counter').html(resp[1]);
  20. }
  21. }
  22. });
  23. } else {
  24. $('#popUpWindow').modal('show');
  25. }
  26. },
  27. });
  28. });
  29. });

PHP – Update Database (update.php)

The below PHP code updates and stores the user’s id in the likes or dislikes column based on the user’s choice in the database table.
  1. <?php session_start(); ?>
  2. <?php include('db.php');?>
  3. <?php
  4. if(isset($_POST) && !empty($_POST)) {
  5. $action = trim($_POST['action']);
  6. $post_id = trim($_POST['post_id']);
  7. if($action != "" && $post_id != "") {
  8. try {
  9. $qry = "select * from `post_list` where `id`=$post_id";
  10. $res = mysqli_query($con, $qry);
  11. if(mysqli_num_rows($res) == 1) {
  12. $row = mysqli_fetch_object($res);
  13. $likers = array_filter(explode(',', $row->likes), function($value) { return $value !== ''; });
  14. $dislikers = array_filter(explode(',', $row->dislikes), function($value) { return $value !== ''; });
  15. $like_count = count($likers);
  16. $dislike_count = count($dislikers);
  17. if($action == 'like') {
  18. if(!in_array($_SESSION['sess_user_id'], $likers)) {
  19. array_push($likers, $_SESSION['sess_user_id']);
  20. $like_count += 1;
  21. }
  22. $index = array_search(''.$_SESSION['sess_user_id'].'', $dislikers);
  23. if($index !== false) {
  24. unset($dislikers[$index]);
  25. $dislike_count -= 1;
  26. }
  27. } else if($action == 'dislike') {
  28. if(!in_array($_SESSION['sess_user_id'], $dislikers)) {
  29. array_push($dislikers, $_SESSION['sess_user_id']);
  30. $dislike_count += 1;
  31. }
  32. $index = array_search($_SESSION['sess_user_id'], $likers);
  33. if($index !== false) {
  34. unset($likers[$index]);
  35. $like_count -= 1;
  36. }
  37. }
  38. $qry = "update `post_list` set `likes`='".implode(',', $likers)."', `dislikes`='".implode(',', $dislikers)."' where `id`=$post_id";
  39. mysqli_query($con, $qry);
  40. if(mysqli_affected_rows($con) == 1) {
  41. echo $like_count.'|'.$dislike_count;
  42. }
  43. }
  44. } catch (Exception $e) {
  45. echo "Error : " .$e->getMessage();
  46. }
  47. }
  48. }
  49. ?>

Check Session  (check-session.php)

check-session.php returns the id of the user which is stored in the session after logging in. If it returns nothing then a login form will display for login to the website.
  1. <?php
  2. session_start();
  3. echo @$_SESSION['sess_user_id'];
  4. ?>

Bootstrap Login Form –  (login.php)

  1. <div class="container">
  2. <div class="modal fade" id="popUpWindow">
  3. <div class="modal-dialog">
  4. <div class="modal-content">
  5. <!-- header -->
  6. <div class="modal-header">
  7. <button type="button" class="close" data-dismiss="modal">&times;</button>
  8. <h3 class="modal-title">Login Form</h3>
  9. </div>
  10. <!-- body -->
  11. <div class="modal-header">
  12. <form role="form" method="post" id="loginform">
  13. <div class="form-group">
  14. <input type="text" id="username" class="form-control" placeholder="Username" />
  15. <input type="password" id="password" class="form-control" placeholder="Password" />
  16. </div>
  17. </form>
  18. </div>
  19. <!-- footer -->
  20. <div class="modal-footer">
  21. <button type="submit" class="btn btn-primary btn-block login">Log In</button>
  22. </div>
  23. </div>
  24. </div>
  25. </div>
  26. </div>

Login with Ajax –  (mtb.js)

The below Ajax code is responsible for user validation using Ajax.
  1. $('button.login').click(function() {
  2. $.ajax({
  3. url: 'login.php',
  4. method: 'POST',
  5. data: {username:$('#username').val(), password:$('#password').val()},
  6. success: function(resp) {
  7. resp = $.trim(resp);
  8. alert(resp);
  9. if(resp == "loggedin") {
  10. $('#popUpWindow').modal('hide');
  11. alert('You are logged in now.');
  12. }
  13. }
  14. });
  15. });

PHP –  User Validation (login.php)

The below PHP code checks if the user is valid or not based on the username and password.
  1. <?php session_start(); ?>
  2. <?php include('db.php');?>
  3. <?php
  4. $msg = "";
  5. if(isset($_POST) && !empty($_POST)) {
  6. $username = trim($_POST['username']);
  7. $password = trim($_POST['password']);
  8. if($username != "" && $password != "") {
  9. try {
  10. $query = "select * from `user_login` where `username`='$username' and `password`='$password'";
  11. $res = mysqli_query($con, $query);
  12. if(mysqli_num_rows($res) == 1) {
  13. $row = mysqli_fetch_object($res);
  14. $_SESSION['sess_user_id'] = $row->id;
  15. $_SESSION['sess_username'] = $row->username;
  16. $_SESSION['sess_name'] = $row->name;
  17. echo 'loggedin';
  18. } else {
  19. echo "Invalid username and password!";
  20. }
  21. } catch (Exception $e) {
  22. echo "Error : ".$e->getMessage();
  23. }
  24. } else {
  25. $msg = "Both fields are required!";
  26. }
  27. }
  28. ?>

Log Out – (logout.php)

Destroy the all sessions when users click on the logout link.
  1. <?php
  2. session_start();
  3. session_destroy();
  4. header("location: ./");
  5. ?>
Try the live demo on – like-dislike rating system using jQuery, Ajax, PHP and MySQL from the below Demo link. Also, you can download the complete source code from below Download link. Please like and share this tutorial with others.

0 comments:

Post a Comment