Star Rating System with jQuery, Ajax, PHP and MySQL

Star Rating System is very useful to get user feedback about the product or service. With the rating system, the user can rate the product by selecting the star. It helps service provider to improve their service based on the rating provided by the customer. Mostly, the 5 stars are used to rate between 1 to 5 for the rating system. Besides the provider, the Five-Star rating system helps the buyer to select a quality product based on the rate provided by the other customers.

You can easily implement the dynamic 5 Star Rating System with the database using PHP and MySQL. If you want to integrate the review system, star rating definitely add an extra value to make it user-friendly. In this tutorial, we will show you how to build a rating system with 5 star using jQuery, Ajax, PHP, and MySQL.

In the example script, we will create a dynamic star rating system with PHP and integrate it into the post details page.

  • Fetch specific post data from the database and displayed on the webpage.
  • Add 5-star rating to the respective post.
  • Submit user’s rating using jQuery and Ajax.
  • Store rating number in the database with PHP and MySQL.
  • Display rating number and average rating with the star.

Before getting started to build a star rating system, take a look at the files structure.

star_rating_system_php/
├── dbConfig.php
├── index.php
├── rating.php
├── js/
│   ├── jquery.min.js
└── css/
    └── style.css

Create Database Tables

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

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

CREATE TABLE `posts` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `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',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

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

CREATE TABLE `rating` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `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',
 `submitted` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The following code is used to connect the database using PHP and MySQL. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your database credentials.

<?php 
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$dbName     "codexworld";

// Create database connection
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

// Check connection
if ($db->connect_error) {
    die(
"Connection failed: " $db->connect_error);
}

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

In the post page, we will display information about the specific post and add 5 Star rating for the respective post.

  • Fetch the post and rating information from the database based on a specific ID.
  • Display post details and star rating to rate the post. Also, the existing rating number and the average rating is shown under the post title.
<?php 
// Include the database config file
include_once 'dbConfig.php';

$postID 1// It will be changed with dynamic value

// Fetch the post and rating info from database
$query "SELECT p.*, COUNT(r.rating_number) as rating_num, FORMAT((SUM(r.rating_number) / COUNT(r.rating_number)),1) as average_rating FROM posts as p LEFT JOIN rating as r ON r.post_id = p.id WHERE p.id = $postID GROUP BY (r.post_id)";
$result $db->query($query);
$postData $result->fetch_assoc();
?>

Submit Rating Number:
Once the user clicks on the star, the rating number is posted to the server-side script via Ajax request.

<div class="container">
    <h1><?php echo $postData['title']; ?></h1>
    <div class="rate">
        <input type="radio" id="star5" name="rating" value="5" <?php echo ($postData['average_rating'] >= 5)?'checked="checked"':''?>>
        <label for="star5"></label>
        <input type="radio" id="star4" name="rating" value="4" <?php echo ($postData['average_rating'] >= 4)?'checked="checked"':''?>>
        <label for="star4"></label>
        <input type="radio" id="star3" name="rating" value="3" <?php echo ($postData['average_rating'] >= 3)?'checked="checked"':''?>>
        <label for="star3"></label>
        <input type="radio" id="star2" name="rating" value="2" <?php echo ($postData['average_rating'] >= 2)?'checked="checked"':''?>>
        <label for="star2"></label>
        <input type="radio" id="star1" name="rating" value="1" <?php echo ($postData['average_rating'] >= 1)?'checked="checked"':''?>>
        <label for="star1"></label>
    </div>
    <div class="overall-rating">
        (Average Rating <span id="avgrat"><?php echo $postData['average_rating']; ?></span>
        Based on <span id="totalrat"><?php echo $postData['rating_num']; ?></span> rating)</span>
    </div>
	
    <div class="content"><?php echo $postData['content']; ?></div>
</div>

Include the jQuery library to use Ajax.

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

Initiate Ajax request to post the rating number to the server-side script (rating.php) for the database insertion.

  • Get the ID from the post data.
  • Get the rating number from the selected radio input.
  • Send rating number and post ID to rating.php script using jQuery Ajax.
  • Based on the response, update the rating number and average rating info.
<script>
$(function() {
    $('.rate input').on('click', function(){
        var postID = <?php echo $postData['id']; ?>;
        var ratingNum = $(this).val();
		
        $.ajax({
            type: 'POST',
            url: 'rating.php',
            data: 'postID='+postID+'&ratingNum='+ratingNum,
            dataType: 'json',
            success : function(resp) {
                if(resp.status == 1){
                    $('#avgrat').text(resp.data.average_rating);
                    $('#totalrat').text(resp.data.rating_num);
					
                    alert('Thanks! You have rated '+ratingNum+' to "<?php echo $postData['title']; ?>"');
                }else if(resp.status == 2){
                    alert('You have already rated to "<?php echo $postData['title']; ?>"');
                }
				
                $( ".rate input" ).each(function() {
                    if($(this).val() <= parseInt(resp.data.average_rating)){
                        $(this).attr('checked', 'checked');
                    }else{
                        $(this).prop( "checked", false );
                    }
                });
            }
        });
    });
});
</script>

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.

  • Retrieve the post ID and rating number with PHP $_POST method.
  • Get the current IP address using $_SERVER['REMOTE_ADDR'].
  • Check duplicate rating submission based on the Post ID and IP address.
  • Insert rating information in the database.
  • Fetch rating data from the database.
  • Return the response in JSON format.
<?php 
// Include the database config file
include_once 'dbConfig.php';

if(!empty(
$_POST['postID']) && !empty($_POST['ratingNum'])){
    
// Get posted data
    
$postID $_POST['postID'];
    
$ratingNum $_POST['ratingNum'];
    
    
// Current IP address
    
$userIP $_SERVER['REMOTE_ADDR'];
    
    
// Check whether the user already submitted the rating for the same post
    
$query "SELECT rating_number FROM rating WHERE post_id = $postID AND user_ip = '".$userIP."'";
    
$result $db->query($query);
    
    if(
$result->num_rows 0){
        
// Status
        
$status 2;
    }else{
        
// Insert rating data in the database
        
$query "INSERT INTO rating (post_id,rating_number,user_ip) VALUES ('".$postID."', '".$ratingNum."', '".$userIP."')";
        
$insert $db->query($query);
        
        
// Status
        
$status 1;
    }
    
    
// Fetch rating details from the database
    
$query "SELECT COUNT(rating_number) as rating_num, FORMAT((SUM(rating_number) / COUNT(rating_number)),1) as average_rating FROM rating WHERE post_id = $postID GROUP BY (post_id)";
    
$result $db->query($query);
    
$ratingData $result->fetch_assoc();
    
    
$response = array(
        
'data' => $ratingData,
        
'status' => $status
    
);
    
    
// Return response in JSON format
    
echo json_encode($response);
}
?>

Like Dislike Rating System with jQuery, Ajax and PHP

Conclusion

This simple star rating system script helps you to integrate a dynamic rating system on the website. You can use this 5 Star Rating system in PHP to allows the user to rate product or services without page refresh using jQuery and Ajax. The functionality of this PHP star rating system can be easily enhanced as per your needs.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

27 Comments

  1. Tac Said...
  2. Sonu Said...
  3. Salman Iqbal Said...
  4. Kevin Said...
  5. Zeehan Akhtar Mohammed Said...
  6. Kaustav Said...
  7. Heena Said...
  8. Greg Said...
  9. Hitesh Said...
  10. Hosean Mogammdi Said...
  11. Jason Said...
  12. David Said...
  13. Ganesh Babu Jonnadula Said...
  14. Kurt Said...
  15. Sara Said...
  16. Sara Said...
    • CodexWorld Said...
  17. Rintu Mohan Said...
  18. Murat Said...
  19. Vghe Said...
  20. Rookey Said...
  21. Rookey Said...
    • CodexWorld Said...
  22. Danny Said...
  23. Clm Said...
  24. Shimii Said...
  25. Landon Said...

Leave a reply

keyboard_double_arrow_up