Building Star Rating in PHP Using JQuery And AJAX

Star Rating in PHP Using JQuery And AJAX is extremely valuable to get client criticism about the item or administration. With the rating framework, the client can rate the item by choosing the star. It causes a specialist organization to improve its administration dependent on the rating gave by the client. Generally, the 5 stars are utilized to rate between 1 to 5 for the rating framework. Other than the supplier, the Five-Star rating framework encourages the purchaser to choose a quality item dependent on the rate gave by different clients.

You can without much of a stretch execute the dynamic 5 Star Rating System with the database utilizing PHP and MySQL. On the off chance that you need to coordinate the survey framework, star rating unquestionably enhance make it easy to understand. In this instructional exercise, we will tell you the best way to assemble a rating framework with 5 stars utilizing jQuery, Ajax, PHP, and MySQL.

In the model content, we will make a powerful star rating framework with PHP and incorporate it into the post subtleties page.

  • Get explicit post information from the database and shown on the page.
  • Add 5-star rating to the particular post.
  • Submit user’s rating using jQuery and Ajax.
  • Store rating number in the database with PHP and MySQL.
  • Show rating number and normal rating with the star.
Building Star Rating in PHP Using JQuery And AJAX

Create Database Tables

Two tables are required to store the post and rating information in the database.

The following SQL creates a posts table with some basic fields in the MySQL database.

Table 1 : Posts
CREATE TABLE `posts` (
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `content` text COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',

The following SQL creates a rating table with a parent identifier (post_id) in the MySQL database.

CREATE TABLE `rating` (
 `post_id` int(11) NOT NULL,
 `rating_number` int(11) NOT NULL,
 `user_ip` varchar(20) COLLATE utf8_unicode_ci NOT NULL COMMENT 'User IP Address',
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

//Database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '1234';
$dbName = 'demo_new';

//Connect with the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
    die('Connect error:'.$db->connect_error);

Star Rating System in the Post Page (index.php )

include_once 'dbConfig.php';
//Fetch rating deatails from database
$query = "SELECT rating_number, FORMAT((total_points / rating_number),1) as average_rating FROM post_rating WHERE post_id = 1 AND status = 1";
$result = $db->query($query);
$ratingRow = $result->fetch_assoc();
<!DOCTYPE html>
<html lang="en">
<link href="rating.css" rel="stylesheet" type="text/css">
<script src=""></script>
<script type="text/javascript" src="rating.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
        starLength: '5',
        initialValue: '',
        callbackFunctionName: 'processRating',
        imageDirectory: 'images/',
        inputAttr: 'postID'

function processRating(val, attrVal){
        type: 'POST',
        url: 'rating.php',
        data: 'postID='+attrVal+'&ratingPoints='+val,
        dataType: 'json',
        success : function(data) {
            if (data.status == 'ok') {
                alert('You have rated '+val);
                alert('Some problem occured, please try again.');
<style type="text/css">
    .overall-rating{font-size: 14px;margin-top: 5px;color: #8e8d8d;}
    <h1>Rating System</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>
    <p>POST 1.</p>

Save Rating Data in the Database (rating.php)

The rating.php file is called by the Ajax request to insert rating number in the database.

include_once 'dbConfig.php';
    $postID = $_POST['postID'];
    $ratingNum = 1;
    $ratingPoints = $_POST['ratingPoints'];
    //Check the rating row with same post ID
    $prevRatingQuery = "SELECT * FROM post_rating WHERE post_id = ".$postID;
    $prevRatingResult = $db->query($prevRatingQuery);
    if($prevRatingResult->num_rows > 0):
        $prevRatingRow = $prevRatingResult->fetch_assoc();
        $ratingNum = $prevRatingRow['rating_number'] + $ratingNum;
        $ratingPoints = $prevRatingRow['total_points'] + $ratingPoints;
        //Update rating data into the database
        $query = "UPDATE post_rating SET rating_number = '".$ratingNum."', total_points = '".$ratingPoints."', modified = '".date("Y-m-d H:i:s")."' WHERE post_id = ".$postID;
        $update = $db->query($query);
        //Insert rating data into the database
        $query = "INSERT INTO post_rating (post_id,rating_number,total_points,created,modified) VALUES(".$postID.",'".$ratingNum."','".$ratingPoints."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')";
        $insert = $db->query($query);
    //Fetch rating deatails from database
    $query2 = "SELECT rating_number, FORMAT((total_points / rating_number),1) as average_rating FROM post_rating WHERE post_id = ".$postID." AND status = 1";
    $result = $db->query($query2);
    $ratingRow = $result->fetch_assoc();
        $ratingRow['status'] = 'ok';
        $ratingRow['status'] = 'err';
    //Return json formatted rating data
    echo json_encode($ratingRow);

Building Star Rating in PHP Using JQuery And AJAX

These are the Main files and rest you can download from the below download button and if you have any concern regarding code then please put your comment down in the comment section.


This simple star rating system script helps you to integrate a dynamic rating system on the website you can utilize this 5 Star Rating framework in PHP to permits the client to rate items or administrations without page invigorate utilizing jQuery and Ajax. The usefulness of this PHP star rating framework can be effectively upgraded according to your necessities


  1. Kanhaiya Kumar July 12, 2020
  2. Kanhaiya Kumar July 12, 2020
  3. rahul Brahmankar July 12, 2020
  4. santosh kumar July 12, 2020
  5. ajay tiwari July 12, 2020
  6. Prahlad July 12, 2020
  7. rahul July 13, 2020
  8. akhil Bansal July 13, 2020
  9. Saboor July 13, 2020
  10. Amit Gupta July 17, 2020

Add Comment