Product Rating System using PHP – Now a days rating system fill the biggest place in all companies and online shoppings like YouTube, Flipkart etc. So we have develop product based rating system using php. Many students are also try to new type of rating system and i also expose new rating system.

product based rating system using php

Only registered user can rate the products, no facilities for guest( to prevent spamming). Seperate products section and user can rate a product just once. Coding is done using PDO classes with submit data via AJAX.

Demo

Product Based Rating System using PHP

Here some PDO object will be used to develop the product rating system. All the users are rating the each and every products in all categories. Here all the PDO will be initialized in database connection. Totally three users are developed and manage every users rating the every products.

There are many products we have developed and options available in rating the products. Every activity and ratings are stores in our database files and users also read and write the rating system.

Database Configuration file

First we have create one database, we want must three tables in this database to communicate product rating systems review. create rating_system database.

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 ;

Connecting Database

Here used PDO used to communicate the database.


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 = "vetripandi";

Rating the Products

When user select the products, its show the previous rating reviews also.

<!-- 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>

Execute the Database query in AJAX

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);
?>
Click to download
Click to download

We hope you have some idea in develop product rating system.