How To Use Five Star Rating System With Jquery In PHP

admin_img Posted By Bajarangi soft , Posted On 18-09-2020

Dynamic star rating data posting using PHP Script with Ajax JQuery By using simple logic we can easily implement Star rating system using Jquery and Ajax and we can store data in database.

rating_system


Let's Create.
1.Create two table in product_management database

CREATE TABLE `jewellery_rating` (
`rating_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`rating` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE `joyalukkas` (
`id` int(11) NOT NULL,
`user_name` varchar(300) NOT NULL,
`address` text NOT NULL,
`product` text NOT NULL,
`image` varchar(225) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2.Create index.php and implement html script in that file as below.
<!DOCTYPE html>
<html>
<head>
    <title>PHP Rating System using Ajax</title>
    <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.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>

<body>
<div class="container" style="width:800px;">
    <h2 align="center">PHP Rating System using Ajax</h2>
    <br/>
    <div class="messgae"></div>
  
    <br />
    <br />
</div>
</body>
</html>


3.Create database.php file to store rating index to database.
<?php

//database.php
$connect = mysqli_connect("localhost", "root", "", "product_management");
if(isset($_POST["index"], $_POST["user_id"]))
{
    $user_id = $_POST["user_id"];
    $rating = $_POST["index"];
    $insert = 'INSERT INTO jewellery_rating(user_id, rating) VALUES ("'.$user_id.'", "'.$rating.'")';
    $result = mysqli_query($connect, $insert);
//    $row = mysqli_fetch_assoc($result);
    if(isset($result))
    {
        echo 'done';
    }
}

?>

4.Create script in index.php to store the rate of that particular product.
onclick stars that should save in jquery , so when user give rating to particular product and it will click onparticular number star then at that time ajax called to request and it will send data to server and it will insert rating data into jewellery_rating table.
//index.php
<script>
    $(document).ready(function(){
        $(document).on('mouseenter', '.rating', function(){
            var index = $(this).data("index");
            var user_id = $(this).data('user_id');
            remove_background(user_id);
            for(var count = 1; count<=index; count++)
            {
                $('#'+user_id+'-'+count).css('color', '#ffcc00');//add colors
            }
        });

        function remove_background(user_id)
        {
            for(var count = 1; count <= 5; count++)
            {
                $('#'+user_id+'-'+count).css('color', '#ccc');//remove the /colors
            }
        }

        $(document).on('mouseleave', '.rating', function(){
            var index = $(this).data("index");
            var user_id = $(this).data('user_id');
            var rating = $(this).data("rating");
            remove_background(user_id);
            //alert(rating);
            for(var count = 1; count<=rating; count++)
            {
                $('#'+user_id+'-'+count).css('color', '#ffcc00');//add color
            }
        });

        $(document).on('click', '.rating', function(){
            var index = $(this).data("index");
            var user_id = $(this).data('user_id');
            $.ajax({
                url:"db.php",
                method:"POST",
                data:{index:index, user_id:user_id},
                success:function(data)
                {
                    console.log(data);
                    if(data == 'done')
                    {
                        // load_business_data();
                        $(".messgae").html('<div class="alert alert-success">\n' +
                            '  <strong>Success!</strong> You have<a href="#" class="alert-link"> rate '+index +' out of 5</a>.\n' +
                            '</div>');
                    }
                }
            });

        });

    });
</script>

5.After inserting rating data to database we need to fetch that on web page so user can see how much they rated for that particular data so below implement in index.php
//index.php
<?php
    $connect = mysqli_connect("localhost", "root", "", "product_management");

    $query = "
SELECT * FROM joyalukkas ORDER BY id DESC
";
    $result = mysqli_query($connect, $query);
    $output = '';
    foreach($result as $row)
    {
        $rating = count_rating($row['id'], $connect);
        $color = '';
        $output .= '
<div class="col-md-3"><img src="'.$row['image'].'" alt="Girl in a jacket" width="150" height="150"></div>
 <h3 class="text-primary">'.$row['user_name'].'</h3>
 <ul class="list-inline" data-rating="'.$rating.'" title="Average Rating - '.$rating.'">
 ';

        for($count=1; $count<=5; $count++)
        {
            if($count <= $rating)
            {
                $color = 'color:#ffcc00;';
            }
            else
            {
                $color = 'color:#ccc;';
            }
            $output .= '<li title="'.$count.'" id="'.$row['id'].'-'.$count.'" data-index="'.$count.'"  data-user_id="'.$row['id'].'" data-rating="'.$rating.'" class="rating" style="cursor:pointer; '.$color.' font-size:26px;">&#9733;</li>';
        }
        $output .= '
 </ul>
 <p>'.$row["address"].'</p>
 <label style="text-danger">'.$row["product"].'</label>
 <hr />
 ';
    }
    echo $output;

    function count_rating($user_id, $connect)
    {
        $output = 0;
        $query = "SELECT AVG(rating) as rating FROM jewellery_rating WHERE user_id = '".$user_id."'";
        $result = mysqli_query($connect, $query);
        $rowcount=mysqli_num_rows($result);
        $total_row = $rowcount;
        if($total_row > 0)
        {
            foreach($result as $row)
            {
                $output = round($row["rating"]);
            }
        }
        return $output;
    }
    ?>

6.Complete code of rating system
<!DOCTYPE html>
<html>
<head>
    <title>PHP Rating System using Ajax</title>
    <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.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>

<body>
<div class="container" style="width:800px;">
    <h2 align="center">PHP Rating System using Ajax</h2>
    <br/>
    <div class="messgae"></div>
    <?php
    $connect = mysqli_connect("localhost", "root", "", "school_management");

    $query = "
SELECT * FROM joyalukkas ORDER BY id DESC
";
    $result = mysqli_query($connect, $query);
    $output = '';
    foreach($result as $row)
    {
        $rating = count_rating($row['id'], $connect);
        $color = '';
        $output .= '
<div class="col-md-3"><img src="'.$row['image'].'" alt="Girl in a jacket" width="150" height="150"></div>
 <h3 class="text-primary">'.$row['user_name'].'</h3>
 <ul class="list-inline" data-rating="'.$rating.'" title="Average Rating - '.$rating.'">
 ';
        for($count=1; $count<=5; $count++)
        {
            if($count <= $rating)
            {
                $color = 'color:#ffcc00;';
            }
            else
            {
                $color = 'color:#ccc;';
            }
            $output .= '<li title="'.$count.'" id="'.$row['id'].'-'.$count.'" data-index="'.$count.'"  data-user_id="'.$row['id'].'" data-rating="'.$rating.'" class="rating" style="cursor:pointer; '.$color.' font-size:26px;">&#9733;</li>';
        }
        $output .= '
 </ul>
 <p>'.$row["address"].'</p>
 <label style="text-danger">'.$row["product"].'</label>
 <hr />
 ';
    }
    echo $output;
    function count_rating($user_id, $connect)
    {
        $output = 0;
        $query = "SELECT AVG(rating) as rating FROM jewellery_rating WHERE user_id = '".$user_id."'";
        $result = mysqli_query($connect, $query);
        $rowcount=mysqli_num_rows($result);
        $total_row = $rowcount;
        if($total_row > 0)
        {
            foreach($result as $row)
            {
                $output = round($row["rating"]);
            }
        }
        return $output;
    }
    ?>
    <br />
</div>
</body>
</html>

<script>
    $(document).ready(function(){
        $(document).on('mouseenter', '.rating', function(){
            var index = $(this).data("index");
            var user_id = $(this).data('user_id');
            remove_background(user_id);
            for(var count = 1; count<=index; count++)
            {
                $('#'+user_id+'-'+count).css('color', '#ffcc00');
            }
        });

        function remove_background(user_id)
        {
            for(var count = 1; count <= 5; count++)
            {
                $('#'+user_id+'-'+count).css('color', '#ccc');
            }
        }

        $(document).on('mouseleave', '.rating', function(){
            var index = $(this).data("index");
            var user_id = $(this).data('user_id');
            var rating = $(this).data("rating");
            remove_background(user_id);
            //alert(rating);
            for(var count = 1; count<=rating; count++)
            {
                $('#'+user_id+'-'+count).css('color', '#ffcc00');
            }
        });

        $(document).on('click', '.rating', function(){
            var index = $(this).data("index");
            var user_id = $(this).data('user_id');
            $.ajax({
                url:"db.php",
                method:"POST",
                data:{index:index, user_id:user_id},
                success:function(data)
                {
                    console.log(data);
                    if(data == 'done')
                    {
                        // load_business_data();
                        $(".messgae").html('<div class="alert alert-success">\n' +
                            '  <strong>Success!</strong> You have<a href="#" class="alert-link"> rate '+index +' out of 5</a>.\n' +
                            '</div>');
                    }               }
            });

        });

    });
</script>

Related Post