Star Rating System is beneficial to get user feedback about the services and products. Therefore, with this system, the user can review and rate the product by selecting the star. So, it helps the service providers to improve their service based on the rating provided by the customer. Usually, there is a five-star rating system that we can use to rate between 1 to 5 for the rating system. Also, the Five-Star rating system helps the buyer to select a quality product based on the rate provided by the other customers.
You can rapidly implement the dynamic 5 Star Rating System with the database using PHP and MySQL. If you want to integrate the review system, star rating adds an extra value to make it user-friendly. With the help of the following tutorial, you can quickly build a rating system with 5 stars using jQuery, Ajax, PHP, and MySQL.
In the sample script, we will make a dynamic star rating system with PHP and unify it into the post details page.
- Fetch specific post data from the database and displayed it on the webpage.
- Add a 5-star rating to the respective post.
- Submit the user’s rating using jQuery and Ajax.
- Store the rating number in the database with PHP and MySQL.
- Show the rating number and average rating with the star.
Before starting to build a star rating system, let’s take a look at the file structure.
star_rating_system_php/ ├── dbConfig.php ├── index.php ├── rating.php ├── js/ │ ├── jquery.min.js └── css/ └── style.css
Create Database Tables
You need to store the post and rating information in the database.
1. The following SQL will make a posts table with some necessary 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 will create 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)
You can use the following code 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 = "allsweb"; // 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)
On the posting page, we will display information about the specific post and add a 5 Star rating for the particular post.
- Get the rating details from the database based on a specific ID.
- Display post details and star ratings to rate the post. Besides, 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(); ?>
SEE ALSO: Build an HTML5 Video Player with Custom Controls
Submit Rating Number:
Once the user clicks on the star, it will post the rating number 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.
- According to 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 the rating number in the database.
- Retrieve the post ID and rating number with PHP $_POST method.
- Fetch the current IP address using $_SERVER[‘REMOTE_ADDR’].
- Check duplicate rating submission based on the Post ID and IP address.
- Insert rating details in the database.
- Get 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); } ?>
SEE ALSO: Confirmation Before Closing of Tab/Browser using JavaScript
Conclusion
Firstly, this rating system will help you to integrate a dynamic rating system on the website. Secondly, you can use this 5 Star Rating system in PHP to permit the user to rate products or services without page refresh using jQuery and Ajax. At last, this feature of this PHP star rating system can be easily enhanced as per your needs.
Also, read our previous blog- Redirect non-www to www & HTTP to HTTPS using .htaccess file