Jquery star rating tutorial using php and mysql

This is a very simple and quick tutorial on how to create star ratings very easily using jquery And store visitors vote in database to display product popularity.This is a sample script, Here i did not use very good UI, I just focus on creating dynamic star rating feature using PHP and Mysql.

I created a sample database where visitors vote will be store and Using those votes i’ll display average rating of product, Script created in Core PHP and Mysql so that you can easily integrate in your web based project.



star-rating
Sample rating table structure.

CREATE TABLE IF NOT EXISTS `rating` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `vote` float NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1

In this tutorial i used a jquery star rating plugin to display star rating as UI part you can explore more UI rating feature by this official rating plugin. It also support bootstrap responsive feature.
http://www.jqueryrain.com/?d8VUtmAN

Create sample UI file with some demo products and it’s rating.

 <table border=1>
 <tr><td >
    <img src="img/p1.jpeg">
    <h3>Product-1</h3> 
   <input value="0" type="number" class="rating" min=0 max=5 step=0.1 data-size="md" data-stars="5" productId=1>
        </td>
   <td> 
   <img src="img/p2.jpeg"> 
     <h3>Product-2</h3> 
    <input value="0" type="number" class="rating" min=0 max=5 step=0.1 data-size="md" data-stars="5" productId=2>
    </td>
    </tr></table>

After that include required rating libraries(css & js).

 <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet">
<link href="css/star-rating.min.css" media="all" rel="stylesheet" type="text/css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="js/star-rating.min.js" type="text/javascript"></script>

Apply jquery code when ever user give rating to product then one ajax request will be go to server with productId and given vote and you need to store these values in your database.

<script type="text/javascript">
        $(function(){
               $('.rating').on('rating.change', function(event, value, caption) {
                productId = $(this).attr('productId');
                $.ajax({
                  url: "rating.php",
                  dataType: "json",
                  data: {vote:value, productId:productId, type:'save'},
                  success: function( data ) {
                     alert("rating saved");
                  },
              error: function(e) {
                // Handle error here
                console.log(e);
              },
              timeout: 30000  
            });
              });
        });
    </script>

Create server file rating.php, Where you’ll write rating save and fetch function.

<?php
function connect() {
$hostname = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
  $con = mysqli_connect($hostname, $username, $password, $dbname);	
  return $con;
}
 
function getRatingByProductId($con, $productId) {
	$query = "SELECT SUM(vote) as vote, COUNT(vote) as count from rating WHERE product_id = $productId";
 
      $result = mysqli_query($con, $query);
      $resultSet = mysqli_fetch_assoc($result);
      if($resultSet['count']>0) {
      	$data['avg'] = $resultSet['vote']/$resultSet['count'];
      	$data['totalvote'] = $resultSet['count'];
      } else {
      	$data['avg'] = 0;
      	$data['totalvote'] = $resultSet['count'];
      }
      return $data;
 
}
if(isset($_REQUEST['type'])) {
	if($_REQUEST['type'] == 'save') {
		$vote = $_REQUEST['vote'];
		$productId = $_REQUEST['productId'];
	      $query = "INSERT INTO rating (product_id, vote) VALUES ('$productId', '$vote')";
	      // get connection
	      $con = connect();
	      $result = mysqli_query($con, $query);
	      echo 1; exit;
	} 
}
 
?>



See live demo and download source code.

DEMO

DOWNLOAD

Hope this tutorial will be helpful to make rating system for your web based projects.

If you like this post please don’t forget to subscribe my public notebook for more useful stuff

Enter your email address to subscribe my public notebook..!!

Join 23,411 other subscribers