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.
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
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;
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);
}
In the post page, we will display information about the specific post and add 5 Star rating for the respective post.
<?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.
<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>
The rating.php
file is called by the Ajax request to insert rating number in the database.
$_SERVER['REMOTE_ADDR']
.<?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
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
Hi,
I don’t yet try this but it seems it will be a very good way for my first 5 stars rating I must implement on my web site.
Thanks a lot
brds
How to use in .html page and increase rich snippet value as well as rating value?
Very Nice
how to put the star rating in center alignment??
How hard is this to do with Codeigniter?
Great script! I couldn’t get it to work with several ratings though.
Can you tell me what I have to change if I’d like to have a star rating on another page on my site or several on 1 page?
thanks!
best and easy way coding.
Hey there, first of all: thank you for this great rating system.
Is it possible to change the value of the rating (stars) on the fly? I want to load a div and change
the value of the existing codexworld_rating_widget with a value from my database.
Thank u in advance
how to have five sets of rating each of five stars?
I mean the whole rating system for five different things on the same page.
thank you for this tutorial.
this is very good and easy to use
How can i make the hover work in mobile? Right now in mobile, the star can only be triggered by click.
Great tutorial, really easy to follow and implement. I’d just follow up Rookey’s comment and ask if it’s possible to implement multiple star ratings on a single page?
Thanks.
Hi Codex
Good Tutorial
I need my star to be in the center
Can you tel how to edit the rating.css to make stars always in the center independent of browser size
Thanks
Ganesh
Nice rating systems. is there an easy tweak to display partial star ratings? For example 2.5 shows two and half stars?
thank u sooooooooooooo much
it worked finally 😀
hi,
really useful tutorial ,but we are facing a problem ,
i’m trying to send “attrVal” as PostID which is not an integers only , the postID is a combination of integers and strings
the function doesn’t accept the string and gives the following error “missing )”
so any help please ????
@Sara Open the
rating.php
file and use the single quotes with the$postID
variable in every SQL query where$postID
is used. In this file, you’ll see three SQL query. Update these SQL query like the below.I am using the star rating in a loop. How to get the ‘postID’ value for the particular rating.
Eg: inputAttr:’postID’ instead of inputAttr:$(this).attr(‘postID’)
Hello. thanks for script.
nice.
i tested on php7, apache 2.4, mariadb10 and works, no problem 🙂
thanks.
Nice Script and I need to add the rating while user write the review and display the rating with individual review how can I do
thanks, I helped myself already.
Great script! I couldn’t get it to work with several ratings though.
Can you tell me what I have to change if I’d like to have a star rating on another page on my site or several on 1 page?
thanks!
@Rookey We’ve received many requests on this functionality. We’ll try to publish it soon.
Hi, may I know can I use the star rating simultaneously in different aspect in one page?
For example, I want to include star rating in kind of rating of cleanliness, staff, food, environment.
$query = “SELECT rating_number, FORMAT((total_points / rating_number),1) as average_rating FROM post_rating WHERE post_id = 1 AND status = 1”;
Since the condition is already set, post_id=1 AND status=1, it always shows this result with its own id.
I’m the newbies of doing star rating for the first time, hope I can get the help.
Hi
Thanks for this script.
Have you fix the problem Landon? I’m in the same situation.
And how can i adapte this script if i have multiple product to rate?
clm
how to repeat star rating (each image should to come star rating)?
How can I allow post_id ($postID) be an alphanumeric string instead of only numeric? So far I’ve modified the mysql table so that `post_id` is a VARCHAR(25) field and updated the PHP scripts to wrap $postID in single quotes. I’m missing something though because everything works when I use a number as the postID but *not* if I use something with alpha characters in it.
Example – this:
$prevRatingQuery = “SELECT * FROM post_rating WHERE post_id = “.$postID;
Changed to:
$prevRatingQuery = “SELECT * FROM post_rating WHERE post_id = ‘”.$postID.”‘”;
And this:
$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”).”‘)”;
Changed to:
$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”).”‘)”;
All the queries were updated to wrap $postID in single quotes. I can insert records manually into the table with alphanumeric values for post_id but something is stopping it from working when using the rating scripts.
Thank you.