Product Rating System with PHP MySQL, jQuery & Ajax

by  
Share:
Product rating system with php mysql jquery and Ajax

If you guys use/develop ecommerce system, product rating system is one of their core moudles. Giving user the facility to rate their products makes the website more open and engaing. So In this tutorial I will explain you how to create a product rating system with php, mysql, jquery and Ajax. I have used bootstrap3 framework for quick html integration.

View Demo

Features included in product rating system

These are the list of features available in this product rating system. Check the demo.

  • Only registered user can rate products. No facilities for guest( to prevent spamming).
  • Separate products section.
  • User can rate a product just once.
  • Coding is done using PDO classes.
  • Ratings plugins used from wbotelhos.com
  • Ratings is submitted via Ajax.

Steps to create product rating system

To create product rating system with php, mysql, jquery and Ajax follow these steps.
1.) Create a database named “rating_system” and run this script.

CREATE TABLE IF NOT EXISTS `tbl_users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS `tbl_products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `product_name` varchar(255) NOT NULL,
  `product_price` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`product_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;

CREATE TABLE IF NOT EXISTS `tbl_products_ratings` (
  `ratings_id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `ratings_score` int(11) NOT NULL,
  PRIMARY KEY (`ratings_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;

2) Configure your application basic settings.
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'rating_system');

$dboptions = array(
    PDO::ATTR_PERSISTENT => FALSE,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

try {
  $DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions);
} catch (Exception $ex) {
  echo $ex->getMessage();
  die;
}

// you need to setup the user section yourself. make sure you get the user_id and user_name in session and initialize them in this variable

$USER_ID = 12;
$USER_NAME = "Shahrukh Khan";

3) In products.php page get the products id using $_GET[“id”]
4.) Setup the rating system in products.php
<!-- include the rating javascript file -->
<script src="raty/jquery.raty.js" type="text/javascript"></script>

<!-- to display rating bind this div -->
<div id="prd"></div>
<script>
  $(function() {
    $('#prd').raty({
      number: 5, starOff: 'raty/img/star-off-big.png', starOn: 'raty/img/star-on-big.png', width: 180, scoreName: "score",
    });
  });
</script>

<!-- when user submits the rating fire an ajax event -->
<script>
  $(document).on('click', '#submit', function() {
      var score = $("#score").val();
      if (score.length > 0) {
        $("#rating_zone").html('processing...');
        $.post("update_ratings.php", {
          pid: "<?php echo $_GET["pid"]; ?>",
          uid: "<?php echo $USER_ID; ?>",
          score: score
        }, function(data) {
          if (!data.error) {
            // display the new ratings 
            $("#avg_ratings").html(data.updated_rating);
			// display the success message
            $("#rating_zone").html(data.message).show();
          } else {
            // display the failure message
            $("#rating_zone").html(data.message).show();
          }
        }, 'json'
                );
      } else {
        alert("select the ratings.");
      }
  });
</script>

5) The final step is to grab the query string from products.php (made via ajax call) and execute a database query. On success returns success message, with updated ratings. On failure returns failure message. All these message are returned in json format.
<?php
require_once './config.php';

$pid = intval($_POST["pid"]);
$uid = intval($_POST["uid"]);
$score = intval($_POST["score"]);

$aResponse['error'] = FALSE;
$aResponse['message'] = '';
$aResponse['updated_rating'] = '';

$return_message = "";
$success = FALSE;

$sql = "INSERT INTO `tbl_products_ratings` (`product_id`, `user_id`, `ratings_score`) VALUES "
        . "( :pid, :uid, :score)";
$stmt = $DB->prepare($sql);
try {

  $stmt->bindValue(":pid", $pid);
  $stmt->bindValue(":uid", $uid);
  $stmt->bindValue(":score", $score);
  $stmt->execute();
  $result = $stmt->rowCount();
  if ($result > 0) {
    $aResponse['message'] = "Your rating has been added successfully";
  } else {
    $aResponse['error'] = TRUE;
    $aResponse['message'] = "There was a problem updating your rating. Try again later";
  }
} catch (Exception $ex) {
  $aResponse['error'] = TRUE;
  $aResponse['message'] = $ex->getMessage();
}

if ($aResponse['error'] === FALSE) {
  // now fetch the latest ratings for the product.
  $sql = "SELECT count(*) as count, AVG(ratings_score) as score FROM `tbl_products_ratings` WHERE 1 AND product_id = :pid";
  try {
    $stmt = $DB->prepare($sql);
    $stmt->bindValue(":pid", $pid);
    $stmt->execute();
    $products = $stmt->fetchAll();

    if ($products[0]["count"] > 0) {
      // update ratings
      $aResponse['updated_rating'] = "Average rating <strong>" . round($products[0]["score"], 2) . "</strong> based on <strong>" . $products[0]["count"] . "</strong> users";
    } else {
      $aResponse['updated_rating'] = '<strong>Ratings: </strong>No ratings for this product';
    }
  } catch (Exception $ex) {
    #echo $ex->getMessage();
  }
}

echo json_encode($aResponse);
?>

View the demo, and download the script below.
View Demo
Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

s.shivasurya on

nice one bro!!

Reply
Maxi Capodacqua on

Good job! Thanks for sharing

Reply
Naveen P Suthar on

Nice Script. Good Work!! Thx. for sharing.

Reply
zaid al amin on

nice work using ajax for submiting without refreshing page
that what i need

Reply
Shahrukh Khan on

thank you.

Reply
Vikas Sharma on

Shahrukh Bhai, @wesome tutorial,

thanks ….

Reply
Shahrukh Khan on

Thanks Vikash

Reply
Bhola on

I don’t want to add user_id. without creating a user account it should be allow to rate to user. How is it possible in your script. Plz help

Reply
Shahrukh Khan on

Well that creates a lot of security issues. It spams things. So I think it’s best to use USER_ID

Reply
Kamal on

Without Users you can Use Captcha verification, when someone click on rating system, Popup CAPTCHA box will appear. DONE

Reply
asd on

thank you man

Reply
Shahrukh Khan on

you are welcome

Reply
shashank on

how to get top rated products by its average? Can you help with mysql query?

Reply
Shahrukh Khan on

you need to use order by clause where rating_column DESC

Reply
Jun jun on

Very Nice but how can i implement this using msqli?

Reply
Shahrukh Khan on

Almost same just check the mysqli class method and replace with the respective class method. and please dont forget to change the database connection as well.

Reply
Jun jun on

Sir i need this to covert in msqli please help me thank you

Reply
Ella on

You are awesome

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.