Like unlike Rating System with AngularJS and PHP

With like unlike system you can allow the registered users to give feedback on content.

It helps the webmaster to track the user’s response to the contents whether they like it or not and take action.

In this tutorial, I am creating a like unlike functionality on the page with AnguarlJS and PHP where I will list all records and display total like unlikes count following with buttons.

Like unlike Rating System with AngularJS and PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. Script
  6. Demo
  7. Conclusion

1. Table structure

I am using two tables in the example –

posts table ( All posts records )

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

like_unlike table ( User response on a post )

CREATE TABLE `like_unlike` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `userid` int(11) NOT NULL,
  `postid` int(11) NOT NULL,
  `type` int(2) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a config.php for the database connection.

Completed Code

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. HTML

Create a post list structure and define the required directives.

Define ng-repeat='post in posts' on <div class="post"> to display posts list with like and unlike buttons.

Properties –

  • post.title – Post title
  • post.content – Post content
  • post.likes – Total likes on a post
  • post.unlikes – Total unlikes on a post
  • post.type – User status on a post like or unlike. 1 is for like and 0 is for unlike.

Define two directives on buttons – ng-style and ng-click. With ng-style set color according to post.type and from ng-click call setResponse() where pass post.id and $index.

Completed Code

<body ng-app='myapp'>
 <div class="content" ng-controller='fetchCtrl' >

  <!-- Posts -->
  <div class="post" ng-repeat='post in posts'>
   <h2 >{{ post.title }}</h2>
   <div class="post-text">
    {{ post.content }}
   </div>
   <div class="post-action">
     <!-- Like -->
     <input type="button" value="Like" class="like" ng-style="post.type == 1 && {'color': '#ffa449'}" ng-click='setResponse(post.id,1,$index)' />&nbsp;(<span >{{ post.likes}}</span>)&nbsp;
     <!-- Unlike -->
     <input type="button" value="Unlike" class="unlike" ng-style="post.type == 0 && {'color': '#ffa449'}" ng-click='setResponse(post.id,0,$index)' />&nbsp;(<span >{{ post.unlikes }}</span>)
   </div>
  </div>
 
 </div>
</body>

4. PHP

Create a likeunlike.php file for handling AJAX requests.

For demonstration purpose, I have fixed the value of $userid=5 which you can replace with a $_SESSION variable.

  • If $request == 1 then return all posts with a total like unlike status on a post and also the $userid=5 status.
  • If $request == 2 then update the status on the post according to $_POST['type']. If a record already exists then update it otherwise insert a new record and return total likes unlikes on the post.

Completed Code

<?php
include "config.php";
$data = json_decode(file_get_contents("php://input"));
$request = $data->request;

$userid = 5;
// Get all posts list and like unlike
if($request == 1){ 
  $response_arr = array();     
  $query = "SELECT * FROM posts";     
  $result = mysqli_query($con,$query);
  while($row = mysqli_fetch_array($result)){        
    $postid = $row['id'];        
    $title = $row['title'];        
    $content = $row['content'];        
    $type = -1;
        
    // Checking user status        
    $status_query = "SELECT count(*) as cntStatus,type FROM like_unlike WHERE userid=".$userid." and postid=".$postid;        
    $status_result = mysqli_query($con,$status_query);          
    $status_row = mysqli_fetch_array($status_result);        
    $count_status = $status_row['cntStatus'];        
    if($count_status > 0){            
      $type = $status_row['type'];        
    }
        
    // Count post total likes and unlikes        
    $like_query = "SELECT COUNT(*) AS cntLikes FROM like_unlike WHERE type=1 and postid=".$postid;        
    $like_result = mysqli_query($con,$like_query);        
    $like_row = mysqli_fetch_array($like_result);        
    $total_likes = $like_row['cntLikes'];
        
    $unlike_query = "SELECT COUNT(*) AS cntUnlikes FROM like_unlike WHERE type=0 and postid=".$postid;        
    $unlike_result = mysqli_query($con,$unlike_query);        
    $unlike_row = mysqli_fetch_array($unlike_result);        
    $total_unlikes = $unlike_row['cntUnlikes'];
        
    $response_arr[] = array("id" => $postid, 
               "title" => $title, 
               "content" => $content, 
               "likes" => $total_likes, 
               "unlikes" => $total_unlikes, 
               "type" => $type);    
   }
   echo json_encode($response_arr);    
   exit;
}

// Update user response on a post
if($request == 2){ 
  $postid = $data->postid; 
  $type = $data->type;
  // Check entry within table 
  $query = "SELECT COUNT(*) AS cntpost FROM like_unlike WHERE postid=".$postid." and userid=".$userid;
  $result = mysqli_query($con,$query); 
  $fetchdata = mysqli_fetch_array($result); 
  $count = $fetchdata['cntpost'];
  
  if($count == 0){    
    $insertquery = "INSERT INTO like_unlike(userid,postid,type) values(".$userid.",".$postid.",".$type.")";    
    mysqli_query($con,$insertquery); 
  }else {    
    $updatequery = "UPDATE like_unlike SET type=" . $type . " where userid=" . $userid . " and postid=" . $postid;    
    mysqli_query($con,$updatequery); 
  }
  // count numbers of like and unlike in post 
  $query = "SELECT COUNT(*) AS cntLike FROM like_unlike WHERE type=1 and postid=".$postid; 
  $result = mysqli_query($con,$query); 
  $fetchlikes = mysqli_fetch_array($result); 
  $totalLikes = $fetchlikes['cntLike'];
  $query = "SELECT COUNT(*) AS cntUnlike FROM like_unlike WHERE type=0 and postid=".$postid; 
  $result = mysqli_query($con,$query); 
  $fetchunlikes = mysqli_fetch_array($result); 
  $totalUnlikes = $fetchunlikes['cntUnlike'];
  $return_arr = array("likes"=>$totalLikes,
       "unlikes"=>$totalUnlikes,
       "type" => $type );
  echo json_encode($return_arr); 
  exit;
}

5. Script

Define two methods getPosts() and setResponse().

getPosts() – Fetch all posts by sending $http service request where pass request: 1 as data. Initialize $scope.posts with response.data on successful callback.

setResponse() – Send $http service request to update the users response on a post where pass postid: postid, type: type, request: 2 as data.

On successful callback update the $scope.posts values according to the index value.

Completed Code

var fetch = angular.module('myapp', []);
fetch.controller('fetchCtrl', ['$scope', '$http', function ($scope, $http) {
 
 // Fetch post data
 $scope.getPosts = function(){
 
   $http({
     method: 'post',
     url: 'likeunlike.php',
     data: {request: 1}
   }).then(function successCallback(response) {
 
     $scope.posts = response.data;
   });

  } 

  $scope.getPosts(); // Fetch post data
 
  // Update user response on a post
  $scope.setResponse = function(postid,type,index){
 
   $http({
    method: 'post',
    url: 'likeunlike.php',
    data: {postid: postid,type: type, request: 2}
   }).then(function successCallback(response) {
   
     // Update total likes unlikes values on the post
     $scope.posts[index].likes=response.data.likes;
     $scope.posts[index].unlikes=response.data.unlikes;
     $scope.posts[index].type=response.data.type;
   });
  }
 }
]);

6. Demo

View Demo


7. Conclusion

In the demonstration, I have created like unlike system where a user can either like or unlike a post at a time for this I have fixed the userid value to 5 which you can replace with the $_SESSION variable value in the PHP script.

If you found this tutorial helpful then don't forget to share.