How to make a Like Dislike System - PHP

In this article you will learn How can you make your own Like and Dislike system. We are going to make the logic in Php.
So if you don't know, PHP was a popular language for making websites backend. Even the world's biggest social network, Facebook was built in Php. But today, Php is not used much. Even its importance is decreasing day by day and it's becoming dead.
So Why did I made this in Php? Well the answer is simple. I know Php. Infact Php is a good language. You can even imagine the popularity of Facebook, which was made in Php. And its not bad to learn Php because if you are able to make the logics in it, it is definitely going to help you in other languages. There's no minus point for learning Php.
So, you must have seen like dislike systems on various social networks like YouTube. So 2 months back I wanted to create my own blog and I created it! I started from scratch and designed everything of it one by one as the ideas hit me. You can even have a look at it. TheShiveshNetwork I created this site piece by piece and designed it. And yeah this was my first complete website. With login system and few inbuilt features. Well I know this site contains many bugs but they can be fixed by giving some time to them. Also I am telling this because I am not a kind of person who will keep you in confusion. I am still learning to code. But I love to build things and this site is for that.

The blog was getting completed day by day. So, the thing that I needed after a few days for this blog was a rating system. Where users can like or dislike the blog. So I started searching for tutorials on google and youtube to find the perfect thing that I wanted. Because I told, this was my first website so I needed a reference to understand how things are going to work.

After visiting many places, I couldn't find anything that could completely satisfy what I was thinking. The codes online even had lot of bugs. But one plus point, I had got my idea to use the things needed for making it and bring those things together. So, I started.

PHP Like Dislike System. MrDevKnown. Like and Dislike complete code.
First of all, I created a mysql table to store the rating of posts. The table structure is as

Firstly, make a Mysql table named "posts" Download

Then, make a Mysql table named "rating_info" Download

Next, I connected to the mysql database in php and started writing my logic.

Finally, this was the thing I created. I was highly satisfied wuth its working. And I guess this is the best and complete like dislike system tutorial on the web with a free code. Just download, modify and use it. No need to waste your time on which I wasted weeks :)

Note: I have also combined login , signup and user authentication check and provided in the code below.
    
        
// The code. Just copy from here. Replace "<!--" by "<?"
<?php 
session_start();

<!-- First We will see user authentication with login. -->

// initializing variables
$username = "";
$email = "";
$user_id = "";
$errors = array(); 

$db = mysqli_connect('localhost', 'root', '', 'test');

if (isset($_POST['reg_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $email = mysqli_real_escape_string($db, $_POST['email']);
  $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);

  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array
  if (empty($username)) { array_push($errors, "Username is required"); }
  if (empty($email)) { array_push($errors, "Email is required"); }
  if (empty($password_1)) { array_push($errors, "Password is required"); }
  if ($password_1 != $password_2) {
	array_push($errors, "The two passwords do not match");
  }

  // first check the database to make sure 
  // a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
  $result = mysqli_query($db, $user_check_query);
  $user = mysqli_fetch_assoc($result);
  
  if ($user) { // if user exists
    if ($user['username'] === $username) {
      array_push($errors, "Username already exists");
    }

    if ($user['email'] === $email) {
      array_push($errors, "email already exists");
    }
  }

  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
  	$password = md5($password_1);

  	$query = "INSERT INTO users (username, email, password) 
  			  VALUES('$username', '$email', '$password')";
  	mysqli_query($db, $query);
  	$_SESSION['username'] = $username;
  	$_SESSION['success'] = "You are now logged in";
  	header('location: main.php');
  }
}


// LOGIN USER
if (isset($_POST['login_user'])) {
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db, $_POST['password']);
  
    if (empty($username)) {
        array_push($errors, "Username is required");
    }
    if (empty($password)) {
        array_push($errors, "Password is required");
    }
  
    if (count($errors) == 0) {
        $password = md5($password);
        $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
        $results = mysqli_query($db, $query);

        if (mysqli_num_rows($results) == 1) {
          $_SESSION['loggedin'] = true;
          $_SESSION['username'] = $username;
          $_SESSION['success'] = "You are now logged in";
          header('location: main.php');
        }else {
            array_push($errors, "Wrong username/password combination");
        }
    }
}


if (!$db) {
  die("Error connecting to database: " . mysqli_connect_error($db));
  exit();
}


if (isset($_SESSION['loggedin'])) {
  $user_id = $_SESSION['username'];
}

if (isset($_SESSION['success'])) {
// if user clicks like or dislike button
  if (isset($_POST['action'])) {
    $post_id = $_POST['post_id'];
    $action = $_POST['action'];
    switch ($action) {
      case 'like':
          $sql="INSERT INTO rating_info VALUES ('$user_id', $post_id, 'like')";
            $sql1 = "SELECT * FROM rating_info WHERE user_id='$user_id' AND post_id=$post_id AND rating_action='dislike'";
            $result = mysqli_query($db, $sql1);
            if (mysqli_num_rows($result) > 0) {
              $sql = "UPDATE rating_info SET rating_action='like' WHERE user_id='$user_id' AND post_id=$post_id AND rating_action='dislike'";
            }
          break;
      case 'dislike':
            $sql="INSERT INTO rating_info VALUES ('$user_id', $post_id, 'dislike')";
            $sql1 = "SELECT * FROM rating_info WHERE user_id='$user_id' AND post_id=$post_id AND rating_action='like'";
            $result = mysqli_query($db, $sql1);
            if (mysqli_num_rows($result) > 0) {
              $sql = "UPDATE rating_info SET rating_action='dislike' WHERE user_id='$user_id' AND post_id=$post_id AND rating_action='like'";
            }
          break;
      case 'unlike':
            $sql="DELETE FROM rating_info WHERE user_id='$user_id' AND post_id=$post_id";
          break;
      case 'undislike':
            $sql="DELETE FROM rating_info WHERE user_id='$user_id' AND post_id=$post_id";
        break;
      default:
        break;
    }

    // execute query to effect changes in the database ...
    mysqli_query($db, $sql);
    echo getRating($post_id);
    exit(0);
  }
}

// Get total number of likes for a particular post
function getLikes($id)
{
  global $db;
  $sql = "SELECT COUNT(*) FROM rating_info 
  		  WHERE post_id = $id AND rating_action='like'";
  $rs = mysqli_query($db, $sql);
  $result = mysqli_fetch_array($rs);
  return $result[0];
}

// Get total number of dislikes for a particular post
function getDislikes($id)
{
  global $db;
  $sql = "SELECT COUNT(*) FROM rating_info 
  		  WHERE post_id = $id AND rating_action='dislike'";
  $rs = mysqli_query($db, $sql);
  $result = mysqli_fetch_array($rs);
  return $result[0];
}

// Get total number of likes and dislikes for a particular post
function getRating($id)
{
  global $db;
  $rating = array();
  $likes_query = "SELECT COUNT(*) FROM rating_info WHERE post_id = $id AND rating_action='like'";
  $dislikes_query = "SELECT COUNT(*) FROM rating_info 
		  			WHERE post_id = $id AND rating_action='dislike'";
  $likes_rs = mysqli_query($db, $likes_query);
  $dislikes_rs = mysqli_query($db, $dislikes_query);
  $likes = mysqli_fetch_array($likes_rs);
  $dislikes = mysqli_fetch_array($dislikes_rs);
  $rating = [
  	'likes' => $likes[0],
  	'dislikes' => $dislikes[0]
  ];
  return json_encode($rating);
}

// Check if user already likes post or not
function userLiked($post_id)
{
  global $db;
  global $user_id;
  $sql = "SELECT * FROM rating_info WHERE user_id='$user_id' AND post_id=$post_id AND rating_action='like'";
  $result = mysqli_query($db, $sql);
  if (mysqli_num_rows($result) > 0) {
  	return true;
  }else{
  	return false;
  }
}

// Check if user already dislikes post or not
function userDisliked($post_id)
{
  global $db;
  global $user_id;
  $sql = "SELECT * FROM rating_info WHERE user_id='$user_id' AND post_id=$post_id AND rating_action='dislike'";
  $result = mysqli_query($db, $sql);
  if (mysqli_num_rows($result) > 0) {
  	return true;
  }else{
  	return false;
  }
}

$sql = "SELECT * FROM posts";
$result = mysqli_query($db, $sql);
// fetch all posts from database
// return them as an associative array called $posts
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);

?>
<!--DOCTYPE html-->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>php tutorial - like dislike system</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
  <div class="container">
<!--php if (isset($_SESSION['success'])) : ?-->
   <!--php foreach ($posts as $post): ?-->
   	<div class="post">
    <a href="item.php" class="title tahoma">
      <!--php echo $post['title']; ?-->
    </a>
    <br>
      <div class="post-info">
      	<i <?php if (userLiked($post['id'])): ?>
      		  class="fa fa-thumbs-up like-btn"
      	  <!--php else: ?-->
      		  class="fa fa-thumbs-o-up like-btn"
      	  <!--php endif ?-->
      	  data-id="<!--php echo $post['id'] ?-->"></i>
      	<span class="likes"><!--php echo getLikes($post['id']); ?--></span>
      	
      	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

      	<i 
      	  <?php if (userDisliked($post['id'])): ?>
      		  class="fa fa-thumbs-down dislike-btn"
      	  <!--php else: ?-->
      		  class="fa fa-thumbs-o-down dislike-btn"
      	  <!--php endif ?-->
      	  data-id="<!--php echo $post['id'] ?-->"></i>
      	<span class="dislikes"><!--php echo getDislikes($post['id']); ?--></span>
      </div>
   	</div>
   <!--php endforeach ?-->

   <!--php else : ?-->
    <!--php foreach ($posts as $post): ?-->
   	<div class="post">
    <a href="item.php" class="title tahoma">
      <!--php echo $post['title']; ?-->
    </a>
    <br>
      <div class="post-info">
      	<a onclick="nfunc()"><i class="fa fa-thumbs-o-up like-btn" data-id="<?php echo $post['id'] ?>"></i></a>
      	<span class="likes"><!--php echo getLikes($post['id']); ?--></span>
      	
      	&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

      	<a onclick="nfunc()"><i class="fa fa-thumbs-o-down dislike-btn"
      	  data-id="<?php echo $post['id'] ?>"></i></a>
      	<span class="dislikes"><!--php echo getDislikes($post['id']); ?--></span>
      </div>
   	</div>
   <!--php endforeach ?-->
   <!--php endif ?-->
  </div>
    </div>
</body>
<script>
  $(document).ready(function(){

// if the user clicks on the like button ...
$('.like-btn').on('click', function(){
  var post_id = $(this).data('id');
  $clicked_btn = $(this);
  if ($clicked_btn.hasClass('fa-thumbs-o-up')) {
  	action = 'like';
  } else if($clicked_btn.hasClass('fa-thumbs-up')){
  	action = 'unlike';
  }
  $.ajax({
  	url: 'index.php',
  	type: 'post',
  	data: {
  		'action': action,
  		'post_id': post_id
  	},
  	success: function(data){
  		res = JSON.parse(data);
  		if (action == "like") {
  			$clicked_btn.removeClass('fa-thumbs-o-up');
  			$clicked_btn.addClass('fa-thumbs-up');
  		} else if(action == "unlike") {
  			$clicked_btn.removeClass('fa-thumbs-up');
  			$clicked_btn.addClass('fa-thumbs-o-up');
  		}
  		// display the number of likes and dislikes
  		$clicked_btn.siblings('span.likes').text(res.likes);
  		$clicked_btn.siblings('span.dislikes').text(res.dislikes);

  		// change button styling of the other button if user is reacting the second time to post
  		$clicked_btn.siblings('i.fa-thumbs-down').removeClass('fa-thumbs-down').addClass('fa-thumbs-o-down');
  	}
  });		

});

// if the user clicks on the dislike button ...
$('.dislike-btn').on('click', function(){
  var post_id = $(this).data('id');
  $clicked_btn = $(this);
  if ($clicked_btn.hasClass('fa-thumbs-o-down')) {
  	action = 'dislike';
  } else if($clicked_btn.hasClass('fa-thumbs-down')){
  	action = 'undislike';
  }
  $.ajax({
  	url: 'index.php',
  	type: 'post',
  	data: {
  		'action': action,
  		'post_id': post_id
  	},
  	success: function(data){
  		res = JSON.parse(data);
  		if (action == "dislike") {
  			$clicked_btn.removeClass('fa-thumbs-o-down');
  			$clicked_btn.addClass('fa-thumbs-down');
  		} else if(action == "undislike") {
  			$clicked_btn.removeClass('fa-thumbs-down');
  			$clicked_btn.addClass('fa-thumbs-o-down');
  		}
  		// display the number of likes and dislikes
  		$clicked_btn.siblings('span.likes').text(res.likes);
  		$clicked_btn.siblings('span.dislikes').text(res.dislikes);
  		
  		// change button styling of the other button if user is reacting the second time to post
  		$clicked_btn.siblings('i.fa-thumbs-up').removeClass('fa-thumbs-up').addClass('fa-thumbs-o-up');
  	}
  });	

});

});

</script>
</html>
        
    

0 Comments