Building Star Rating in PHP Using JQuery And AJAX

0
Shares
Building Star Rating in PHP Using JQuery And AJAX
3.6 (71.31%) 398 votes

Rating system is very useful when it comes to knowing what your audience think of your contents. And it’s just not about only contents, users rate different products based on star rating in PHP. This not only allows to differentiate how good or bad a product is, but it also helps owner to understand drawbacks in the product.

Most of the websites, eCommerce stores in particular have implementing this feature to obtain customer reviews through it. It not only gives better understand of customers’ needs, but also help to understand whether the product meets customer expectations or not.

However, in this PHP tutorial, we’ll build a simple star rating in PHP with functionality to reduce chances of multiple votes by a single user. And to prevent multiple votes, we’ll store the each user’s IP address and set cookies in user’s browser.

To Create this demo, we’ll need following.

  1. Database
  2. Javascript
  3. CSS
  4. img

First, start by login into phpmyadmin – http://localhost/phpmyadmin

Now find database and click on create button. Next, import rating.sql in your database.

Once you import the database, next step is to put JS and CSS file into your project directory.

Start Code Integration

  1. index.php
  2. connection.php
  3. rating.php

Index.php

<?php 

include_once 'connection.php'; 

//Fetch rating deatails from database 

$query = "SELECT rating_number, FORMAT((total_points / rating_number),1) as average_rating FROM view_rating WHERE post_id = 1 AND status = 1"; 

$result = $db->query($query); 

$ratingRow = $result->fetch_assoc(); 

?> 

<!DOCTYPE html> 

<html lang="en"> 

<head> 

<link href="css/rating.css" rel="stylesheet" type="text/css"> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 

<script type="text/javascript" src="js/rating.js"></script> 

<script language="javascript" type="text/javascript"> 

$(function() { 

    $("#rating_star").spaceo_rating_widget({ 

        starLength: '5', 

        initialValue: '', 

        callbackFunctionName: 'processRating', 

        imageDirectory: 'img/', 

        inputAttr: 'post_id' 

    }); 

}); 

function processRating(val, attrVal){ 

    $.ajax({ 

        type: 'POST', 

        url: 'rating.php', 

        data: 'post_id=1&points='+val, 

        dataType: 'json', 

        success : function(data) { 

            if (data.status == 'ok') { 

                alert('You have rated '+val+' to SPACE-O'); 

                $('#avgrat').text(data.average_rating); 

                $('#totalrat').text(data.rating_number); 

            }else{ 

                alert('please after some time.'); 

            } 

        } 

    }); 

} 

</script> 

<style type="text/css"> 

    .overall-rating{font-size: 14px;margin-top: 5px;color: #8e8d8d;} 

</style> 

<title>SAPCE-O - Rating Blog</title> 

</head> 

<body> 

    <h1>SAPCE-O - Rating Blog</h1> 

    <input name="rating" value="0" id="rating_star" type="hidden" postID="1" /> 

    <div class="overall-rating">(Average Rating <span id="avgrat"><?php echo $ratingRow['average_rating']; ?></span> 

    Based on <span id="totalrat"><?php echo $ratingRow['rating_number']; ?></span>  rating)</span></div> 

     

</body> 

</html>

Description : 

Step 1 : <script type="text/javascript" src="js/rating.js"></script> 

Step 2 : <link href="css/rating.css" rel="stylesheet" type="text/css"> 

Step 3 : <script>       src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 

Step 4 : 

<script language="javascript" type="text/javascript"> 

$(function() { 

    $("#rating_star").spaceo_rating_widget({ 

        starLength: '5', 

        initialValue: '', 

        callbackFunctionName: 'processRating', 

        imageDirectory: 'img/', 

        inputAttr: 'post_id' 

    }); 

}); 

function processRating(val, attrVal){ 

    $.ajax({ 

        type: 'POST', 

        url: 'rating.php', 

        data: 'post_id=1&points='+val, 

        dataType: 'json', 

        success : function(data) { 

            if (data.status == 'ok') { 

                alert('You have rated '+val+' to SPACE-O'); 

                $('#avgrat').text(data.average_rating); 

                $('#totalrat').text(data.rating_number); 

            }else{ 

                alert('please after some time.'); 

            } 

        } 

    }); 

} 

</script> 

Connection.php

define('HOST', 'localhost'); 

define('USERNAME', 'root'); 

define('PASSWORD', 'ur48x'); 

define('DATABASE_NAME', 'rating');

//Connect and select the database 

$db = new mysqli(HOST, USERNAME, PASSWORD, DATABASE_NAME); 

if ($db->connect_error) { 

    die("Connection failed: " . $db->connect_error); 

}

NOTE: change value of HOST , USERNAME , PASSWORD , DATABASE_NAME after change run your connection.php file in browser. If you got any error, then you might put value wrong.

Rating.php

Description :- in this file rating save into database with AJAX.

include_once 'connection.php'; 

if(!empty($_POST['points'])){ 

    $post_id = $_POST['post_id']; 

    $rating_default_number = 1; 

    $points = $_POST['points']; 

     

    //Check the rating row with same post ID 

    $prevRatingQuery = "SELECT * FROM view_rating WHERE post_id = ".$post_id; 

    $prevRatingResult = $db->query($prevRatingQuery); 

    if($prevRatingResult->num_rows > 0): 

        $prevRatingRow = $prevRatingResult->fetch_assoc(); 

        $rating_default_number = $prevRatingRow['rating_number'] + $rating_default_number; 

        $points = $prevRatingRow['total_points'] + $points; 

        //Update rating data into the database 

        $query = "UPDATE view_rating SET rating_number = '".$rating_default_number."', total_points = '".$points."', modified = '".date("Y-m-d H:i:s")."' WHERE post_id = ".$post_id; 

        $update = $db->query($query); 

    else: 

        //Insert rating data into the database 

        $query = "INSERT INTO view_rating (post_id,rating_number,total_points,created,modified) VALUES(".$post_id.",'".$rating_default_number."','".$points."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')"; 

        $insert = $db->query($query); 

    endif; 

     

    //Fetch rating deatails from database 

    $query2 = "SELECT rating_number, FORMAT((total_points / rating_number),1) as average_rating FROM view_rating WHERE post_id = ".$post_id." AND status = 1"; 

     

    $result = $db->query($query2); 

    $ratingRow = $result->fetch_assoc(); 

     

    if($ratingRow){ 

        $ratingRow['status'] = 'ok'; 

    }else{ 

        $ratingRow['status'] = 'err'; 

    } 

     

    //Return json formatted rating data 

    echo json_encode($ratingRow); 

}

And done!

This tutorial was just about rating system, but it’s also possible to integrate additional functionality to write a review based on star rating in PHP to get feedbacks from customers. Though, it might be a daunting task, so hire PHP developer if you require technical assistance and implement this feature in your PHP website.

Grab a free copy of PHP star rating system demo from Github.

 
0
Shares
 

Want to Develop Business Website From Scratch? Contact Us Now

3 thoughts on “Building Star Rating in PHP Using JQuery And AJAX

  1. Brosbusters TV

    So, if I want to assign this to different products, the first one would be: postID=”1″, second postID=”2″ etc?

    Thank you for nice tutorial!

    Reply

Leave a Reply

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