PHP Star Rating System with JavaScript

Last modified on June 27th, 2018 by Vincy.

Star rating feature allows the user to grade the service, product, web page, etc. Star rating also allows the owner to understand the user preference and improve the quality accordingly. As for the general users, for example, in a shopping cart application with star rating will help users to search for highly rated products.

PHP-Star-Rating-System-with-JavaScript

Implementing five-star rating using PHP is very simple. We have seen several examples for the PHP star rating system. Let us create a PHP star rating system only with JavaScript without loading jQuery or any third party libraries. See dynamic star rating with jQuery post if you want PHP star rating code with jQuery. In this example, the five-star rating option is shown to collect user rating for restaurants. The user-based rating is added by initializing userid at the beginning of the code. You can replace this initialization by integrating your user authentication code. Once the user rates a restaurant, then he could not rate the same again. 

The restaurant and its ratings are stored in the database. The restaurant results are listed row by row with the star rating option. When the user rates a restaurant the AJAX call will be sent to the PHP to insert rating for the restaurant. The added ratings are displayed with the highlighted stars.

Database Script for Star Rating

This SQL script is with the create statements and the data dump for the tbl_rating and tbl_restaurant tables.

--
-- Table structure for table `tbl_rating`
--

CREATE TABLE `tbl_rating` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL DEFAULT '1',
  `restaurant_id` int(11) NOT NULL,
  `rating` int(2) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `tbl_restaurant`
--

CREATE TABLE `tbl_restaurant` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `tbl_restaurant`
--

INSERT INTO `tbl_restaurant` (`id`, `name`, `address`) VALUES
(1, 'Malaysian Multi Cusine Restaurant', '12, FGH Enclave'),
(2, 'Cafe Monarch', '78, GNT Park');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_rating`
--
ALTER TABLE `tbl_rating`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `tbl_restaurant`
--
ALTER TABLE `tbl_restaurant`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_rating`
--
ALTER TABLE `tbl_rating`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;

--
-- AUTO_INCREMENT for table `tbl_restaurant`
--
ALTER TABLE `tbl_restaurant`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;

List Restaurants with Star Rating Option 

This code is used to fetch the restaurants details from the MySQL database and to list them with the star rating option. The stars are highlighted by hovering on the rating element. On page load, the AJAX call will get and display the user added rating with the highlighted stars. Each restaurant record shows the graphical representation of the five-star rating with overall rating count.

<body onload="showRestaurantData('getRatingData.php')">
    <div class="container">
        <h2>Star Rating System using PHP and Javascript</h2>
        <span id="restaurant_list"></span>
    </div>
</body>

<script type="text/javascript">
	function showRestaurantData(url) {
		var xhttp = new XMLHttpRequest();
		xhttp.onreadystatechange = function() {
			if (this.readyState == 4 && this.status == 200) {
				document.getElementById("restaurant_list").innerHTML = this.responseText;
			}
		};
		xhttp.open("GET", url, true);
		xhttp.send();

	}//endFunction
</script>

getRatingData.php

This PHP code is called with an AJAX request to return the restaurant list with user rating data. It forms HTML response that will be received at the AJAX success callback.

<?php
require_once "db.php";
require_once "functions.php";
// Here the user id is harcoded.
// You can integrate your authentication code here to get the logged in user id
$userId = 1;

$query = "SELECT * FROM tbl_restaurant ORDER BY id DESC";
$result = mysqli_query($conn, $query);

$outputString = '';

foreach ($result as $row) {
    $userRating = userRating($userId, $row['id'], $conn);
    $totalRating = totalRating($row['id'], $conn);
    $outputString .= '
        <div class="row-item">
 <div class="row-title">' . $row['name'] . '</div> <div class="response" id="response-' . $row['id'] . '"></div>
 <ul class="list-inline"  onMouseLeave="mouseOutRating(' . $row['id'] . ',' . $userRating . ');"> ';
    
    for ($count = 1; $count <= 5; $count ++) {
        $starRatingId = $row['id'] . '_' . $count;
        
        if ($count <= $userRating) {
            
            $outputString .= '<li value="' . $count . '" id="' . $starRatingId . '" class="star selected">&#9733;</li>';
        } else {
            $outputString .= '<li value="' . $count . '"  id="' . $starRatingId . '" class="star" onclick="addRating(' . $row['id'] . ',' . $count . ');" onMouseOver="mouseOverRating(' . $row['id'] . ',' . $count . ');">&#9733;</li>';
        }
    } // endFor
    
    $outputString .= '
 </ul>
 
 <p class="review-note">Total Reviews: ' . $totalRating . '</p>
 <p class="text-address">' . $row["address"] . '</p>
</div>
 ';
}
echo $outputString;
?>

Add Star Rating using PHP AJAX

On the click event of the unclicked star element, an AJAX function addRating() to call the PHP file insertRating.php. This AJAX function will pass the restaurant id and the user rating to the PHP file. In PHP, it receives the rating param and inserts ratting data into the database.

<script>
	function addRating(restaurantId, ratingValue) {
		var xhttp = new XMLHttpRequest();

		xhttp.onreadystatechange = function() {
			if (this.readyState == 4 && this.status == 200) {

				showRestaurantData('getRatingData.php');

				if (this.responseText != "success") {
					alert(this.responseText);
				}
			}
		};

		xhttp.open("POST", "insertRating.php", true);
		xhttp.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded");
		var parameters = "index=" + ratingValue + "&restaurant_id="
				+ restaurantId;
		xhttp.send(parameters);
	}
</script>

insertRating.php

<?php
require_once ('db.php');
// Here the user id is harcoded.
// You can integrate your authentication code here to get the logged in user id
$userId = 1;

if (isset($_POST["index"], $_POST["restaurant_id"])) {
    
    $restaurantId = $_POST["restaurant_id"];
    $rating = $_POST["index"];
    
    $checkIfExistQuery = "select * from tbl_rating where user_id = '" . $userId . "' and restaurant_id = '" . $restaurantId . "'";
    if ($result = mysqli_query($conn, $checkIfExistQuery)) {
        $rowcount = mysqli_num_rows($result);
    }
    
    if ($rowcount == 0) {
        $insertQuery = "INSERT INTO tbl_rating(user_id,restaurant_id, rating) VALUES ('" . $userId . "','" . $restaurantId . "','" . $rating . "') ";
        $result = mysqli_query($conn, $insertQuery);
        echo "success";
    } else {
        echo "Already Voted!";
    }
}
?>

Other JavaScript Functions to Create Hover Effect on Five-Star

The following code shows rest of the functions used in this example to create the hover highlighting effects on the five-star elements.

<script>
	function mouseOverRating(restaurantId, rating) {

        resetRatingStars(restaurantId)

        for (var i = 1; i <= rating; i++)
        {
            var ratingId = restaurantId + "_" + i;
            document.getElementById(ratingId).style.color = "#ff6e00";

        }
    }

    function resetRatingStars(restaurantId)
    {
        for (var i = 1; i <= 5; i++)
        {
            var ratingId = restaurantId + "_" + i;
            document.getElementById(ratingId).style.color = "#9E9E9E";
        }
    }

   function mouseOutRating(restaurantId, userRating) {
	   var ratingId;
       if(userRating !=0) {
    	       for (var i = 1; i <= userRating; i++) {
    	    	      ratingId = restaurantId + "_" + i;
    	          document.getElementById(ratingId).style.color = "#ff6e00";
    	       }
       }
       if(userRating <= 5) {
    	       for (var i = (userRating+1); i <= 5; i++) {
	    	      ratingId = restaurantId + "_" + i;
	          document.getElementById(ratingId).style.color = "#9E9E9E";
	       }
       }
    }
</script>

PHP JavaScript Star Rating System Output

This screenshot shows the list of restaurants with the five-star rating system.

PHP-JavaScript-Star-Rating-System-Output

Download

↑ Back to Top

Share this Article