Implement 5 Star Rating System With PHP & JavaScript


Read {count} times since 2020

User ratings are important for your site if you provide downloads of files or run an E-Commerce shop. It is the ratings of other users that tempt your site’s users to buy/download something. So, it is necessary for a site like this to have a Rating System. If you haven’t implemented it yet or want to replace your existing system with a clean one, you’re at the right place.

I give to you, Francium Star : a new member in our Francium Project series. This PHP & JS combined package will provide your site a complete Rating System and it’s very easy to implement.

PHP

The server side consists of 4 PHP files including the index page. Other files are :

  • Fr.star.php
  • config.php
  • ajax_rate.php

Fr.star.php

This is the heart of the rating system. Get the complete file from here.

Database

Create a table named “Fr_star” in your database with the SQL code below :

CREATE TABLE IF NOT EXISTS `Fr_star` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `rate_id` varchar(40) NOT NULL,
  `user_id` varchar(40) NOT NULL,
  `rate` float NOT NULL,
  `rated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
)

config.php

We include the “Fr.star.php” in the file and we provide the database configuration in this file. Example :

<?php
require_once __DIR__ . "/Fr.star.php";

$star = new \Fr\Star(array(
  "db" => array(
    "host" => getenv('OPENSHIFT_MYSQL_DB_HOST'),
    "port" => getenv('OPENSHIFT_MYSQL_DB_PORT'),
    "username" => getenv('OPENSHIFT_MYSQL_DB_USERNAME'),
    "password" => getenv('OPENSHIFT_MYSQL_DB_PASSWORD'),
    "name" => getenv('OPENSHIFT_GEAR_NAME'),
    "table" => "Fr_star"
  )
));

This “config.php” will be included in the AJAX request receiving script as well as the index file.

ajax_rate.php

JavaScript sends AJAX request to this file. This file processes the rating action and tells \Fr\Star to add a rating.

<?php
// This is where AJAX would sent request to

if(isset($_POST['id']) && isset($_POST['rating']) && $_POST['id'] == "index_page"){
  session_start();
  require_once __DIR__ . "/config.php";
  $star->id = $_POST['id'];
  $star->addRating($_SESSION['user_id'], $_POST['rating']);
}

Let me explain what this file do.

  1. It first checks whether values “id” and “rating” exists in the POST data. Also, it checks whether the page ID is “index_page”. It is recomended to check the IDs before rating.
  2. The PHP session is started and the “config.php” is included in the script.
  3. We tell \Fr\Star the ID of the page. Optionally, you can tell this page ID as the second parameter while making the object.
  4. Finally, we call the \Fr\Star::addRating() function to insert the rating data into database.

index.php

This is the page that the user will see. It includes the JavaScript & CSS components of the Francium Star software and shows examples of the usage :

<?php
// Generate a user ID for the session only
session_start();
if(!isset($_SESSION['user_id'])){
  $_SESSION['user_id'] = rand(0, 1024);
}
?>
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="css/Fr.star.css" />
    <script src="//lab.subinsb.com/projects/jquery/core/jquery-latest.js"></script>
    <script src="//lab.subinsb.com/projects/Francium/star/Fr.star.js"></script>
    <script src="js/rate.js"></script>
  </head>
  <body>
    <h1>Francim Star</h1>
    <p>Rating for "index_page" :</p>
    <?php
    require_once __DIR__ . "/config.php";
    $star->id = "index_page";
    
    echo "Rating :";
    echo $star->getRating("userChoose size-1");
    
    echo "<p>Your Rating :</p>";
    echo $star->userRating($_SESSION['user_id']);
    echo "<p>^- You will have to refresh page to update the above value</p>";
    
    echo "<h2>Different Sizes</h2>";
    
    echo "<p>170x30" . $star->getRating("userChoose size-2") . "</p>";
    echo "<p>115x20" . $star->getRating("userChoose size-3") . "</p>";
    echo "<p>55x10" . $star->getRating("userChoose size-4") . "</p>";
    
    echo "<h2>Just Show It !</h2>";
    
    echo "<p>170x30" . $star->getRating("size-2") . "</p>";
    echo "<p>115x20" . $star->getRating("size-3") . "</p>";
    echo "<p>55x10" . $star->getRating("size-4") . "</p>";
    ?>
    <!-- NOTICE - http://subinsb.com/francium-star -->
  </body>
</html>

Note that the above script generates a unique user ID at the beginning of each session. This user ID can be an IP address or the actual user ID of the logged in user.

It is the JavaScript and CSS part of the software that enables the user to rate in the browser. Hence, it is an important part of the software as well.

JavaScript

jQuery is not needed for Francium Star, but it is included to easily send the AJAX request.

Fr.star.js

You can call this file a library of JavaScript and jQuery. Because it will work with native JS as well as like a plugin of jQuery. You will see more about this in the API section of this post.

Get this file from here if you want to include this locally instead of the lab.subinsb.com URL.

If you want a minified version, see this.

js/rate.js

This file makes the rating divs functionable. It also sends the AJAX request.

$(function(){
  $(".Fr-star.userChoose").Fr_star(function(rating){
    $.post("ajax_rate.php", {'id' : 'index_page', 'rating': rating}, function(){
      alert("Rated " + rating + " !!");
    });
  });
});

As I said before, Fr\Star can be used as a jQuery function too.

CSS

There is only one file for styling the rating divs. It’s css/Fr.star.css

*{
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
}
.Fr-star {
  width: 225px;
  height: 40px;
  position: relative;
  background-color: #ccc;
}
.Fr-star[data-title]:hover:after {
  content: attr(data-title);
  padding: 4px 8px;
  color: #333;
  position: absolute;
  left: 0;
  top: 100%;
  z-index: 20;
  white-space: nowrap;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  -moz-box-shadow: 0px 0px 4px #222;
  -webkit-box-shadow: 0px 0px 4px #222;
  box-shadow: 0px 0px 4px #222;
  background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #eeeeee),color-stop(1, #cccccc));
  background-image: -webkit-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -ms-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -o-linear-gradient(top, #eeeeee, #cccccc);
}
.Fr-star .Fr-star-bg{
  position: absolute;
  height: 100%;
  width: 100%;
  background: url(../img/Fr-star.png) repeat;
  background-size: contain;
}
.Fr-star .Fr-star-value{
  height: 100%;
  position: absolute;
  background-color: #ffbe10;
}
.Fr-star.size-2{
  width: 170px;
  height: 30px;
}
.Fr-star.size-3{
  width: 115px;
  height: 20px;
}
.Fr-star.size-4{
  width: 55px;
  height: 10px;
}

There is an image of star that is needed by the above file. Download it from one of the following and move it into a folder called “img” at the root of the site.

When you change the location of the image file, make sure to change the value of the “background” property of “.Fr-star-bg” in the stylesheet too.

API

What you saw above was an example of the rating system. In here, I’m going to show the syntax of each functions that is in PHP and JavaScript/jQuery.

PHP

\Fr\Star::__construct()

$star = new \Fr\Star($config, $id = null);

$id is the page’s ID and $config is an array that will be merged with the default configuration (\Fr\Star::$default_config).

\Fr\Star::addRating()

$star->addRating($user_id, $rating)

$user_id is the user’s ID and $rating is a float value of the rating by the user.

\Fr\Star::getRating()

$star->getRating($html_class = "", $type = "html")

If you would like to add extra CSS “class” to the HTML element created by the above function, add the class name to $html_class parameter.

You can also get the plain rating, instead of an HTML formatted one. The possible values for $type are :

  • rate_value
  • rate_percentage
  • rate_times

I hope you got what the returning values will be when the above values are given.

\Fr\Star::userRating()

$star->userRating($user_id);

Get the rating made by a specific user. The user’s ID should be passed (not optional) by the only parameter $user_id.

JavaScript/jQuery

Fr.star(element, callback_after_rating());

`element` is a DOM object. `callback_after_rating()` is a function that will be called after the user has rated with a parameter containing the rating value.

Example :

Fr.star(document.querySelector(".Fr-star"), function(rating){
  alert("User rated : " + rating);
});

There is no other functions in JavaScript. There is a jQuery wrapper for this function :

$(".Fr-star").Fr_star(function(rating){
  alert("User rated : " + rating);
});

That is everything on Francium Star. This is the first Francium project that uses Object class instead of static. I hope you found what you were looking for.

If you have any suggestions or faced a problem, please feel free to comment. I’ll help 🙂

Show Comments