You have generally seen Star Rating System on various e-commerce or service related websites. This feature is used to know about users thoughts and opinions. This will help to rank your product or content and make online repuatation also.
In this tutorial we going to shown an example to implement dynamic multiple 5 star rating feature on a sinlge page using PHP and MySql.
Supported Features in Multiple Star Rating System:
In this Star rating functionality, we have implement below features:
- Use dynamic multlple star rating on single page
- Allow user to rate any product, service, picture etc.
- Using jQuery, PHP and MySQL to implement star rating system
- Rating scale is 1-4 stars
- Bound single user to rate once on the basis of IP address.
Steps to Create Multiple Star Rating Feature in PHP & MySQL:
1) Create Database Tables:
First create database tables to show product or post data on single page.
1 2 3 4 5 6 |
CREATE TABLE `product` ( `id` int(11) NOT NULL, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; |
Next create another database table to store user ratings value.
1 2 3 4 5 6 7 |
CREATE TABLE `ratings` ( `id` int(11) NOT NULL, `product_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 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; |
‘product_id’ is forign key column in ‘ratings’ database table.
Insert some products or post data in ‘product’ database table to show data on single page.
2) Make database connection:
Add below PHP and MySQL code to make database connection, so that you can show products data on page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php /* database configuration */ $servername = 'localhost'; $username = 'DB_User_Name'; $password = 'DB_Password'; $db = 'DB_Name'; // Create connection $link = new mysqli($servername, $username, $password, $db); // Check connection if ($link->connect_error) { die("Connection failed: " . $link->connect_error); } ?> |
3) Create Index.php File to Show Star Rating:
Now create index.php file and add MySQL query code to fetch products data.
1 2 3 4 5 6 7 |
<?php // Include the database config file include('database.php'); // 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 product as p LEFT JOIN ratings as r ON r.product_id = p.id GROUP BY (p.id) ORDER BY p.id ASC"; $result = $link->query($query); ?> |
Now add below HTML div code to show 5 star rating feature for each post on single index.php page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<div class="container"> <div class="row" style="width:50%"> <?php while($productData = $result->fetch_assoc()){ ?> <div class="column"> <h3><?php echo $productData['title']; ?></h3> </div> <div class="column"> <div class="rate"> <input type="radio" data-id="<?php echo $productData['id']; ?>" id="star5-<?php echo $productData['id']; ?>" name="rating" value="5" <?php echo ($productData['average_rating'] >= 5)?'checked="checked"':''; ?>> <label for="star5-<?php echo $productData['id']; ?>"></label> <input type="radio" data-id="<?php echo $productData['id']; ?>" id="star4-<?php echo $productData['id']; ?>" name="rating" value="4" <?php echo ($productData['average_rating'] >= 4)?'checked="checked"':''; ?>> <label for="star4-<?php echo $productData['id']; ?>"></label> <input type="radio" data-id="<?php echo $productData['id']; ?>" id="star3-<?php echo $productData['id']; ?>" name="rating" value="3" <?php echo ($productData['average_rating'] >= 3)?'checked="checked"':''; ?>> <label for="star3-<?php echo $productData['id']; ?>"></label> <input type="radio" data-id="<?php echo $productData['id']; ?>" id="star2-<?php echo $productData['id']; ?>" name="rating" value="2" <?php echo ($productData['average_rating'] >= 2)?'checked="checked"':''; ?>> <label for="star2-<?php echo $productData['id']; ?>"></label> <input type="radio" data-id="<?php echo $productData['id']; ?>" id="star1-<?php echo $productData['id']; ?>" name="rating" value="1" <?php echo ($productData['average_rating'] >= 1)?'checked="checked"':''; ?>> <label for="star1-<?php echo $productData['id']; ?>"></label> </div> <div class="overall-rating"> (Average Rating <span id="avgrat-<?php echo $productData['id']; ?>"><?php echo $productData['average_rating']; ?></span> Based on <span id="totalrat-<?php echo $productData['id']; ?>"><?php echo $productData['rating_num']; ?></span> rating)</span> </div> </div> <?php } ?> </div> </div> |
Note: Must include jquery.min.js library file execute jQuery AJAX code on star rating click events.
4) Write jQuery Ajax Script Code:
Write down below jQuery Ajax code to record user rating for perticular product or post.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<script> $(function() { $('.rate input').on('click', function(){ var productID = $(this).attr("data-id"); var ratingNum = $(this).val(); $.ajax({ type: 'POST', url: 'ratingAjax.php', data: 'productID='+productID+'&ratingNum='+ratingNum, dataType: 'json', success : function(resp) { if(resp.status == 1){ $('#avgrat-'+productID).text(resp.data.average_rating); $('#totalrat'+productID).text(resp.data.rating_num); alert('You have rated '+ratingNum+' to item successfully'); }else if(resp.status == 2){ alert('You have already submit your rating'); } } }); }); }); </script> |
5) Create Ajax file to Handle Post Request:
Create a ‘ratingAjax.php’ PHP file to handle on click ajax request. On this file we will manage to record user star ratings value in database table.
Also we recording user IP address, so no more duplicate rating will enter in database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php // Include the database config file include('database.php'); if(!empty($_POST['productID']) && !empty($_POST['ratingNum'])){ $productID = $_POST['productID']; $ratingNum = $_POST['ratingNum']; // Current IP address $userIP = $_SERVER['REMOTE_ADDR']; // Check whether the user already submitted the rating or not $query = "SELECT rating_number FROM ratings WHERE product_id = $productID AND user_ip = '".$userIP."'"; $result = $link->query($query); if($result->num_rows > 0){ $status = 2; }else{ // Insert rating data in the database $query = "INSERT INTO ratings (product_id,rating_number,user_ip) VALUES ('".$productID."', '".$ratingNum."', '".$userIP."')"; $insert = $link->query($query); $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 ratings WHERE product_id = $productID GROUP BY (product_id)"; $result = $link->query($query); $ratingData = $result->fetch_assoc(); $response = array( 'data' => $ratingData, 'status' => $status ); echo json_encode($response); } ?> |
Conclusion:
This is simple and easy to configure 5 star rating system. You can easily integrate with in your PHP based web application. If you want to use only single star rating on one page, just remove while loop and edit the MySQL query on index.php page.
Hope this post will help you to build this user rating feature.