In this article, we will learn how to make a 5-star rating system in PHP using the jQuery plugin, It is very useful to give rate today specific content on a website.


Let's follow the following steps to make 5 star rating system in PHP:


Step 1:

We need two database tables myposts and post_rating use the following code to create tables. 


ratting.sql

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 30, 2021 at 09:41 PM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 7.3.25

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `php-tutorial`
--

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

--
-- Table structure for table `myposts`
--

CREATE TABLE `myposts` (
  `id` int(11) NOT NULL,
  `title` varchar(250) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `myposts`
--

INSERT INTO `myposts` (`id`, `title`) VALUES
(1, 'PUBG Mobile India Full Game Download Android And iOS'),
(2, 'Using htaccess to deny access to files and directories'),
(3, 'Bluestacks - How to play mobile games in PC'),
(4, 'Avada - Website Builder For WordPress and WooCommerce download as free'),
(5, 'Download Farming Simulator 19 For Free 2020'),
(6, 'How To Download Free Grand Theft Auto V For PC'),
(7, 'How to download WhatsApp Desktop Or PC'),
(8, 'Pagination in Codeigniter With Bootstrap 4'),
(9, 'How To Use Phone by Google Caller ID and spam protection App'),
(10, 'Minecraft Caves and Clifs 1.17 Android Download'),
(11, 'PHP Date and Time - complete tutorial for beginners'),
(12, 'High-speed Net - Secret Jio APN Settings'),
(13, 'How to upload multiple files into CodeIgniter'),
(14, 'How to upload multiple files with JavaScript and PHP'),
(15, 'Crash Bandicoot 4 Its About Time Full Game For PC Free Download'),
(16, '5 Easy ways to make money online and quickly'),
(17, 'How to Complete 4000 Hours of Watch Time on YouTube This Year As A Small Creator'),
(18, 'Zip And Unzip Files in Windows Pc'),
(19, 'How To Create And Use Google Form'),
(20, 'How To Create A Paytm Account With KYC'),
(21, 'Fixnow - Plumbing HTML Template download as free'),
(22, 'Tips And Tricks to increase PC performance in Windows 10'),
(23, 'Error 0x80070002 - Windows Update'),
(24, 'How to stop automatic updates on Windows 10'),
(25, 'How to speed up your internet speed'),
(26, 'How to make your Facebook profile as private'),
(27, 'The most effective method to Import CSV file data to MySQL in CodeIgniter'),
(28, 'How to create and use UPI'),
(29, '2 Ways to activate Windows 10 FREE without additional software'),
(30, 'Jio Free Data Tricks 2021'),
(31, 'How To Download Among Us PC For Free'),
(32, 'How can I find out which graphics card I have in my PC'),
(33, 'How to Make Money with Your Blog in 2021'),
(34, 'How to Format USB Flash Drive Using CMD'),
(35, 'Troubleshoot problems updating Windows 10'),
(36, 'How to Create a Bootable Pendrive using cmd'),
(37, '15 best Android games on playstore'),
(38, 'OnePlus 8T buyers guide - Everything you need to know'),
(39, 'PUBG Mobile India Version Latest Update- APK Download LinksAvailable on Official Website'),
(40, '7 Ways to Improve Your Computer Performance'),
(41, 'Top 5 Product Review Website Rating Blog HTML5 Templates'),
(42, 'Top 5 best Android emulators for PC and Mac of 2021'),
(43, 'The best Android phones - January 2021'),
(44, 'Cybersecurity Insights Report On 5G release'),
(45, 'GOOGLE adds a list of new partners with BeyondCorp Alliance'),
(46, 'PUBG Mobile India Download Now Available Beta APK'),
(47, 'Very high resolution images free download'),
(48, 'What is Creative Commons'),
(49, 'What is a public domain'),
(50, 'What is royalty free'),
(51, '15 best Chromebook games from Google Play'),
(52, 'Organizations may fail to train their employees against Cybersecurity Threats'),
(53, 'One Identity Highlights Barriers to Adoption of Zero Trust Framework'),
(54, '5 YouTube tricks to help you raise revenue 50 percentage faster Instantly'),
(55, 'PUBG Mobile 2 global version beta update APK OBB download'),
(56, 'The 15 best Android apps available now'),
(57, 'Can not send or receive messages on your Android phone'),
(58, 'Full Galaxy S21 Ultra specs leak no in-box charger allegedly confirmed'),
(59, 'Google Camera Go now brings HDR to budget smartphones Updated'),
(60, 'Sony returns all Cyberpunk 2077 order renewals: Xbox and refunds for all'),
(61, 'How To Calculate CPC and CTR-Formulas'),
(62, 'How to move the mouse cursor with the keyboard in Windows'),
(63, 'Top 10 Indian Information Technology Companies'),
(64, 'Top Indian Information Technology Companies'),
(65, 'TOP MOST EXPENSIVE MOBILE PHONES IN THE WORD'),
(66, 'Best budget gaming headphones'),
(67, '10 WordPress Tips to Make Your Website Secure'),
(68, 'IPhone12 features How Apples snappy new magnet feature works'),
(69, 'How to Not Get Locked Out With Two-Factor Authentication'),
(70, '10 best reminder apps for Android'),
(71, 'BEST STORY-DRIVEN GAMES ON MOBILE'),
(72, 'Best top 5 Smart TVs in India'),
(73, 'SEO-friendly URLs'),
(74, 'What is Canonical Tag Or link SEO'),
(75, 'How to Increase Website Traffic Tips and Tricks');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Step 2:

We need some files in the jQuery 5-star rating plugin, see my project structure 
php-tutorial/
plugins/
┃ ┗ star-ratting/
┃ ┣ fontawesome-stars.css
┃ ┗ jquery.barrating.min.js
┣ index.php
┣ init.php
┗ rating.php

plugins you can download from here https://github.com/antennaio/jquery-bar-rating



Step 3:

make files and put the following codes as it is


init.php

<?php

$host = "localhost";
$user = "root";
$password = "";
$dbname = "demo";

$con = mysqli_connect($host, $user, $password, $dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}


index.php

<?php include "init.php"; ?>
<!DOCTYPE html>
<html>
    <head>
        <title>JQuery Star Ratting in PHP</title>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">
        <!-- you can get from here https://github.com/antennaio/jquery-bar-rating -->
        <link href="plugins/star-ratting/fontawesome-stars.css" rel="stylesheet" type="text/css"/>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js" type="text/javascript"></script>
        <script src="plugins/star-ratting/jquery.barrating.min.js" type="text/javascript"></script>
        <script>
            $(document).ready(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 postid = split_id[1]; // postid

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


            });


        </script>

        <style>

            body{
                background: #ccc;
            }
            .post{
                margin: 20px;
                background: #fff;
                padding: 20px;
            }
        </style>
    </head>
    <body>
        <div class="content">
            <?php
            $userid = 4;
            $query = "SELECT * FROM myposts";
            $result = mysqli_query($con, $query);
            while ($row = mysqli_fetch_array($result)) {
                $postid = $row['id'];
                $title = $row['title'];


                // User rating
                $query = "SELECT * FROM post_rating WHERE postid=" . $postid . " and userid=" . $userid;
                $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 postid=" . $postid;
                $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">
                    <div class="post-text">
                        <?php echo $title; ?>
                    </div>
                    <div class="post-action">
                        <!-- Rating -->
                        <select class='rating' id='rating_<?php echo $postid; ?>' data-id='rating_<?php echo $postid; ?>'>
                            <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 $postid; ?>'><?php echo $averageRating; ?></span>

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

        </div>

    </body>
</html>


rating.php

<?php

include "init.php";

$userid = 4; // User id
$postid = $_POST['postid'];
$rating = $_POST['rating'];

// Check entry within table
$query = "SELECT COUNT(*) AS cntpost FROM post_rating WHERE postid=" . $postid . " and userid=" . $userid;

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

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

// get average
$query = "SELECT ROUND(AVG(rating),1) as averageRating FROM post_rating WHERE postid=" . $postid;
$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);


Output:





Are you facing problems in understanding this article?
You can watch the video. Watch it now