In this PHP tutorial, we are going to add a dynamic star rating to the product. here We have considered a t-shirt as a product. When a customer buys a product that time adds the rating and comment to a product. so we will discuss about a rating.

Step1: Create the database and table.

Now, first, we create a database and create an item_rating table.

CREATE TABLE `item_rating` (
  `id` int(255) NOT NULL,
  `rate_number` varchar(255) NOT NULL,
  `title` varchar(255) NOT NULL,
  `comment` text NOT NULL,
  `created` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step2: create the index.php file.

Second, we will the configuration of the database. after then we will create a rating system using the bootstrap. when we will select star on the click on the star. we will use ajax call to pass data after selecting a star, title, and comment. we will get rating data using the count_rate_data function.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rating";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$sql="SELECT SUM(rate_number) AS total_rate,count(id) as number_record FROM item_rating";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_array($result);

function count_rate_data($rate_number)
{
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "rating";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    $sql="SELECT count(id) as number_record FROM item_rating where rate_number='".$rate_number."' ";
    $result = mysqli_query($conn, $sql);
    $data = mysqli_fetch_array($result);
    if(!empty($data['number_record']))
    {
        return $data['number_record'];
    }
    else{
        return '0';
    }

}
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  <!-- Font Awesome Icon Library -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
* {  box-sizing: border-box;} body {  font-family: Arial;  margin: 0 auto;   max-width: 800px;  padding: 20px; }
.heading {  font-size: 25px;  margin-right: 25px; } .fa {  font-size: 25px; } .checked {  color: orange; }
.side {  float: left;  width: 15%;  margin-top:10px; } .middle {  margin-top:10px;  float: left;  width: 70%; }
.right {  text-align: right; } .row:after {  content: "";  display: table;  clear: both; }
.bar-container {  width: 100%;  background-color: #f1f1f1;  text-align: center;  color: white; }
.bar-5 {width: <?php echo (count_rate_data('5')*100)/$data['number_record'];  ?>%; height: 18px; background-color: #4CAF50;} .bar-4 {width: <?php echo (count_rate_data('4')*100)/$data['number_record'];  ?>%; height: 18px; background-color: #2196F3;} .bar-3 {width: <?php echo (count_rate_data('3')*100)/$data['number_record'];  ?>%; height: 18px; background-color: #00bcd4;}
.bar-2 {width: <?php echo (count_rate_data('2')*100)/$data['number_record'];  ?>%; height: 18px; background-color: #ff9800;} .bar-1 {width: <?php echo (count_rate_data('1')*100)/$data['number_record'];  ?>%; height: 18px; background-color: #f44336;}
label.error{ color:red; } .well{ margin-top: 25px; } .rating_bar{ margin-top: 20px; } .view_rating{ border-bottom: 1px solid #e3e3e3; padding: 20px; } .view_rating:last-child { border: none; }
@media (max-width: 400px) {  .side, .middle {    width: 100%;  }  .right {    display: none;  }}
</style>
<script>
$(document).ready(function(){
    $('.rating .fa-star').click(function(){
        if($(this).hasClass('checked')) {
            $(this).toggleClass('checked');
            $(this).prevAll('.fa-star').addClass('checked');
            $(this).nextAll('.fa-star').removeClass('checked');
        }
        else
        {
            $(this).toggleClass('checked');
            $(this).prevAll('.fa-star').addClass('checked');
        }
        $("#hdnRateNumber").val($('.checked').length);
    });
    $("#frmRating").validate({
        rules: {
            txtTitle: {
                required: true
            },
            txtComment: {
                required: true
            }
        },
        submitHandler: function (form) {
            //Your code for AJAX starts
            jQuery.ajax({
                url: 'saveData.php',
                type: "post",
                data: $(form).serialize(),
                success: function (data) {
                    if(data=="success")
                    {
                        window.location.reload();
                    }
                },
                error: function () {
                }
            });
        }
    });
});
</script>
</head>
<body>

<div class="row">
    <div class="col-lg-3"><img src="t-shirt.jpg" width="175"></div>
    <div class="col-lg-9">
        <p><b>Men Maroon Printed Round Neck T-shirt</b></p>
        <p>PRODUCT DETAILS</p>
        <p>Rust solid T-shirt, has a round neck, long sleeves</p>
        <p>Material & Care</p>
        <p>Cotton</p>
        <p>Machine-wash</p>
    </div>
</div>
<div class="row rating_bar">
    <div class="col-lg-12">
        <div class="row">
            <div class="col-lg-10">
                <p> <span class="btn btn-warning btn-xs"><?php echo $data['total_rate']/$data['number_record'];?></span> average based on <?php echo $data['number_record']; ?> reviews.</p>
            </div>
            <div class="col-lg-2">
                <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">Rate Product</button>
            </div>
        </div>
        <hr style="border:3px solid #f1f1f1">
        <div class="row">
            <div class="col-lg-12">
                <div class="side"><div>5 star</div></div>
                <div class="middle">
                    <div class="bar-container">
                        <div class="bar-5"></div>
                    </div>
                </div>
                <div class="side right"><div><?php echo count_rate_data('5'); ?></div></div>
                <div class="side"><div>4 star</div></div>
                <div class="middle">
                    <div class="bar-container">
                        <div class="bar-4"></div>
                    </div>
                </div>
                <div class="side right"><div><?php echo count_rate_data('4'); ?></div></div>
                <div class="side"><div>3 star</div></div>
                <div class="middle">
                    <div class="bar-container">
                        <div class="bar-3"></div>
                    </div>
                </div>
                <div class="side right"> <div><?php echo count_rate_data('3'); ?></div></div>
                <div class="side"><div>2 star</div></div>
                <div class="middle">
                    <div class="bar-container">
                        <div class="bar-2"></div>
                    </div>
                </div>
                <div class="side right"><div><?php echo count_rate_data('2'); ?></div></div>
                <div class="side"><div>1 star</div></div>
                <div class="middle">
                    <div class="bar-container">
                        <div class="bar-1"></div>
                    </div>
                </div>
                <div class="side right"><div><?php echo count_rate_data('1'); ?></div></div>
            </div>
        </div>
    </div>
</div>

<div class="well">
<?php
$sql="SELECT * FROM item_rating ORDER by id DESC ";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
?>

<div class="row view_rating">
    <div class="col-lg-3">
        <img src="user-dummy.png" width="75">
        <p><?php echo date('d M, Y',strtotime($row['created']));?></p>
    </div>
    <div class="col-lg-9">
        <p><span class="btn btn-warning btn-xs"><?php echo $row['rate_number'];?> <span class="fa fa-star" style="font-size: 12px;"></span></span> <?php echo $row['title'];?></p>
        <p><?php echo $row['comment'];?></p>
    </div>
</div>
<?php } ?>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="rating">
                    <span class="heading">User Rating</span>
                    <span class="fa fa-star"></span>
                    <span class="fa fa-star"></span>
                    <span class="fa fa-star"></span>
                    <span class="fa fa-star"></span>
                    <span class="fa fa-star"></span>
                </div>
                <form name="frmRating" id="frmRating">
                    <div class="form-group">
                        <label for="txtTitle">Title:</label>
                        <input type="hidden" name="hdnRateNumber" id="hdnRateNumber">
                        <input type="text" class="form-control" id="txtTitle" placeholder="Enter Title" name="txtTitle">
                    </div>
                    <div class="form-group">
                        <label for="pwd">Comment:</label>
                        <textarea name="txtComment" id="txtComment" class="form-control" rows="10"></textarea>
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>

</body>
</html>

Step3: Create a saveData.php file.

In this step, we will store data into the database such as rate number, title, and comment.

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rating";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}



if($_POST['txtTitle'] && $_POST['txtComment'])
{

    $rate = $_POST['hdnRateNumber'];
    $title = $_POST['txtTitle'];
    $comment = $_POST['txtComment'];
    $date = date('Y-m-d H:i:s');
    $sql = "INSERT INTO item_rating (rate_number,title,comment,created) VALUES ('".$rate."', '".$title."', '".$comment."','".$date."')";

    if (mysqli_query($conn, $sql) === TRUE) {
        echo "success";
    } else {
        echo "error";
    }

}

?>

Show Demo