Star Rating System In PHP + MySQL + Ajax

To create ⭐  star rating system in PHP + MySQL + Ajax. in this tutorial, i am going to show you how to create star rating system in PHP + MySQL + Ajax. And as well as how to store star rating into MySQL database.

You can use this for create product, post, customer and user 5 ⭐ rating system using PHP + MySQL + jQuery and ajax.

Star ⭐ Rating System In PHP + MySQL + Ajax

  • Step 1 – Start Apache Web Server
  • Step 2 – Create PHP Project
  • Step 3 – Create Table and Database Connection File
  • Step 4 – Create Start Rating Html
    • Create Star Rating HMTL Markup
    • Integrate Star Rating jQuery Plugin
    • Implement Ajax Code to Send Star Rating into Server
  • Step 5 – Store Star Rating into Database
  • Step 6 – Test This PHP App

Step 1 – Start Apache Web Server

Now, you need to start your apache web server. And as well as start Apache and mysql web server. You can see in the image below how to start apache and mysql server:

start xampp apache mysql server
start xampp apache mysql server

Step 2 – Create PHP Project

In step 2, navigate to your xampp/htdocs/ directory. And inside xampp/htdocs/ directory, create one folder. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 3 – Create Table and Database Connection File

In step 3,, you need to create database and table. So run the following sql query to create database and table:

CREATE DATABASE my_db;


CREATE TABLE `posts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `post_rating` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  `rating` int(2) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

Then create a php file that named mydb.php. Which is used to connect phpmyadmin mysql database to project folder(demo).

So, now create mydb.php file and add the below given code into your file:

<?php

    $hName='localhost'; // host name

    $uName='root';   // database user name

    $password='';   // database password

    $dbName = "my_db"; // database name

    $con = mysqli_connect($hName,$uName,$password,"$dbName");

      if(!$con){
          die('Could not Connect MySql Server:' .mysql_error());
      }
?>

Step 4 – Create Star Rating Html

In step 4, create a php file that named index.php. Which is used to display star rating and store star rating to MySQL database in PHP, So add the following code into it:

Create Star Rating HTML Markup

Create star rating html markup and add into index.php file; as shown below:

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
      <title>Get And Display Star Rating In PHP with jQuery Ajax</title>
       <!-- CSS -->
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">

    <link href='https://cdnjs.cloudflare.com/ajax/libs/jquery-bar-rating/1.2.2/themes/fontawesome-stars.min.css' rel='stylesheet' type='text/css'>
     
    <!-- Script -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-bar-rating/1.2.2/jquery.barrating.min.js" integrity="sha512-nUuQ/Dau+I/iyRH0p9sp2CpKY9zrtMQvDUG7iiVY8IBMj8ZL45MnONMbgfpFAdIDb7zS5qEJ7S056oE7f+mCXw==" crossorigin="anonymous"></script>
      <style>
         .content{
 border: 0px solid black;
 border-radius: 3px;
 padding: 5px;
 margin: 0 auto;
 width: 50%;
}

.post{
 border-bottom: 1px solid black;
 padding: 10px;
 margin-top: 10px;
 margin-bottom: 10px;
}

.post:last-child{
 border: 0;
}

.post h1{
 font-weight: normal;
 font-size: 30px;
}

.post a.link{
 text-decoration: none;
 color: black;
}

.post-text{
 letter-spacing: 1px;
 font-size: 15px;
 font-family: serif;
 color: gray;
 text-align: justify;
}
.post-action{
 margin-top: 15px;
 margin-bottom: 15px;
}

.like,.unlike{
 border: 0;
 background: none;
 letter-spacing: 1px;
 color: lightseagreen;
}

.like,.unlike:hover{
 cursor: pointer;
}
      </style>
   </head>
   <body>
      <div class="container">
        <div class="content">

         <?php
         include "db.php";
         $user_id = 10;
         $query = "SELECT * FROM posts";
         $result = mysqli_query($con,$query);
         while($row = mysqli_fetch_array($result)){
          $post_id = $row['id'];
          $title = $row['title'];
          $content = $row['content'];
          $link = $row['link'];

          // User rating
          $query = "SELECT * FROM post_rating WHERE post_id=".$post_id." and user_id=".$user_id;
          $userresult = mysqli_query($con,$query) or die(mysqli_error());
          $fetchRating = mysqli_fetch_array($userresult);
          $rating = $fetchRating['rating'];

          // get average
          $query = "SELECT ROUND(AVG(rating),1) as averageRating FROM post_rating WHERE post_id=".$post_id;
          $avgresult = mysqli_query($con,$query) or die(mysqli_error());
          $fetchAverage = mysqli_fetch_array($avgresult);
          $averageRating = $fetchAverage['averageRating'];

          if($averageRating <= 0){
           $averageRating = "No rating yet.";
          }
         ?>
          <div class="post">
           <h1><a href='<?php echo $link; ?>' class='link' target='_blank'><?php echo $title; ?></a></h1>
           <div class="post-text">
            <?php echo $content; ?>
           </div>
           <div class="post-action">
           <!-- Rating -->
           <select class='rating' id='rating_<?php echo $post_id; ?>' data-id='rating_<?php echo $post_id; ?>'>
            <option value="1" >1</option>
            <option value="2" >2</option>
            <option value="3" >3</option>
            <option value="4" >4</option>
            <option value="5" >5</option>
           </select>
           <div style='clear: both;'></div>
           Average Rating : <span id='avgrating_<?php echo $post_id; ?>'><?php echo $averageRating; ?></span>

           <!-- Set rating -->
          <script type='text/javascript'>
           $(document).ready(function(){
            $('#rating_<?php echo $post_id; ?>').barrating('set',<?php echo $rating; ?>);
           });
          </script>
           </div>
          </div>
         <?php
         }
         ?>

        </div>
      </div>

   </body>
</html>

Integrate Star Rating jQuery Plugin

Add the following lines jQuery star rating js library in html form:

Implement Ajax Code to Send Star Rating into Server

Implement jQuery ajax code for send star rating to server, so add into index.php file; as shown below:

      <script type="text/javascript">
        $(function() {
         $('.rating').barrating({
          theme: 'fontawesome-stars',
          onSelect: function(value, text, event) {

           // Get element id by data-id attribute
           var el = this;
           var el_id = el.$elem.data('id');

           // rating was selected by a user
           if (typeof(event) !== 'undefined') {
         
             var split_id = el_id.split("_");
             var post_id = split_id[1]; // post_id

             // AJAX Request
             $.ajax({
               url: 'store-star-rating-db.php',
               type: 'post',
               data: {post_id:post_id,rating:value},
               dataType: 'json',
               success: function(data){
                 // Update average
                 var average = data['averageRating'];
                 $('#avgrating_'+post_id).text(average);
               }
             });
           }
          }
         });
        });
      </script>

Complete source code of index.php file; as below:

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
      <title>Get And Display Star Rating In PHP with jQuery Ajax</title>
       <!-- CSS -->
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">

    <link href='https://cdnjs.cloudflare.com/ajax/libs/jquery-bar-rating/1.2.2/themes/fontawesome-stars.min.css' rel='stylesheet' type='text/css'>
     
    <!-- Script -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-bar-rating/1.2.2/jquery.barrating.min.js" integrity="sha512-nUuQ/Dau+I/iyRH0p9sp2CpKY9zrtMQvDUG7iiVY8IBMj8ZL45MnONMbgfpFAdIDb7zS5qEJ7S056oE7f+mCXw==" crossorigin="anonymous"></script>
      <style>
         .content{
 border: 0px solid black;
 border-radius: 3px;
 padding: 5px;
 margin: 0 auto;
 width: 50%;
}

.post{
 border-bottom: 1px solid black;
 padding: 10px;
 margin-top: 10px;
 margin-bottom: 10px;
}

.post:last-child{
 border: 0;
}

.post h1{
 font-weight: normal;
 font-size: 30px;
}

.post a.link{
 text-decoration: none;
 color: black;
}

.post-text{
 letter-spacing: 1px;
 font-size: 15px;
 font-family: serif;
 color: gray;
 text-align: justify;
}
.post-action{
 margin-top: 15px;
 margin-bottom: 15px;
}

.like,.unlike{
 border: 0;
 background: none;
 letter-spacing: 1px;
 color: lightseagreen;
}

.like,.unlike:hover{
 cursor: pointer;
}
      </style>
   </head>
   <body>
      <div class="container">
        <div class="content">

         <?php
         include "mydb.php";
         $user_id = 10;
         $query = "SELECT * FROM posts";
         $result = mysqli_query($con,$query);
         while($row = mysqli_fetch_array($result)){
          $post_id = $row['id'];
          $title = $row['title'];
          $content = $row['content'];
          $link = $row['link'];

          // User rating
          $query = "SELECT * FROM post_rating WHERE post_id=".$post_id." and user_id=".$user_id;
          $userresult = mysqli_query($con,$query) or die(mysqli_error());
          $fetchRating = mysqli_fetch_array($userresult);
          $rating = $fetchRating['rating'];

          // get average
          $query = "SELECT ROUND(AVG(rating),1) as averageRating FROM post_rating WHERE post_id=".$post_id;
          $avgresult = mysqli_query($con,$query) or die(mysqli_error());
          $fetchAverage = mysqli_fetch_array($avgresult);
          $averageRating = $fetchAverage['averageRating'];

          if($averageRating <= 0){
           $averageRating = "No rating yet.";
          }
         ?>
          <div class="post">
           <h1><a href='<?php echo $link; ?>' class='link' target='_blank'><?php echo $title; ?></a></h1>
           <div class="post-text">
            <?php echo $content; ?>
           </div>
           <div class="post-action">
           <!-- Rating -->
           <select class='rating' id='rating_<?php echo $post_id; ?>' data-id='rating_<?php echo $post_id; ?>'>
            <option value="1" >1</option>
            <option value="2" >2</option>
            <option value="3" >3</option>
            <option value="4" >4</option>
            <option value="5" >5</option>
           </select>
           <div style='clear: both;'></div>
           Average Rating : <span id='avgrating_<?php echo $post_id; ?>'><?php echo $averageRating; ?></span>

           <!-- Set rating -->
          <script type='text/javascript'>
           $(document).ready(function(){
            $('#rating_<?php echo $post_id; ?>').barrating('set',<?php echo $rating; ?>);
           });
          </script>
           </div>
          </div>
         <?php
         }
         ?>

        </div>
      </div>
      <script type="text/javascript">
        $(function() {
         $('.rating').barrating({
          theme: 'fontawesome-stars',
          onSelect: function(value, text, event) {

           // Get element id by data-id attribute
           var el = this;
           var el_id = el.$elem.data('id');

           // rating was selected by a user
           if (typeof(event) !== 'undefined') {
         
             var split_id = el_id.split("_");
             var post_id = split_id[1]; // post_id

             // AJAX Request
             $.ajax({
               url: 'store-star-rating-db.php',
               type: 'post',
               data: {post_id:post_id,rating:value},
               dataType: 'json',
               success: function(data){
                 // Update average
                 var average = data['averageRating'];
                 $('#avgrating_'+post_id).text(average);
               }
             });
           }
          }
         });
        });
      </script>
   </body>
</html>

Step 5 – Store Star Rating into Database

In step 5, create one file that named store-star-rating-db.php file. This php file code will insert/store star rating into mysql database and directory.

So, add the below code into your store-star-rating-db.php file:

<?php

include "mydb.php";

$user_id = 10; // User id
$post_id = $_POST['post_id'];
$rating = $_POST['rating'];

// Check entry within table
$query = "SELECT COUNT(*) AS postCount FROM post_rating WHERE post_id=".$post_id." and user_id=".$user_id;

$result = mysqli_query($con,$query);
$fetchdata = mysqli_fetch_array($result);
$count = $fetchdata['postCount'];

if($count == 0){
 $insertquery = "INSERT INTO post_rating(user_id,post_id,rating) values(".$user_id.",".$post_id.",".$rating.")";
 mysqli_query($con,$insertquery);
}else {
 $updatequery = "UPDATE post_rating SET rating=" . $rating . " where user_id=" . $user_id . " and post_id=" . $post_id;
 mysqli_query($con,$updatequery);
}

// get average
$query = "SELECT ROUND(AVG(rating),1) as averageRating FROM post_rating WHERE post_id=".$post_id;
$result = mysqli_query($con,$query) or die(mysqli_error());
$fetchAverage = mysqli_fetch_array($result);
$averageRating = $fetchAverage['averageRating'];

$return_arr = array("averageRating"=>$averageRating);

echo json_encode($return_arr);

Step 6 – TestThis PHP App

Finally, you need to open your browser and type http://localhost/demo/ this run project on local machine.

Conclusion

To create 5 star ⭐ rating system in PHP + MySQL + Ajax. in this tutorial, You have learned how to create star rating system in PHP + MySQL + Ajax. And as well as how to store star ⭐ rating into MySQL database.

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *