Home > PHP > 5-Star Rating System with PHP, MySQL and jQuery Ajax

5-Star Rating System with PHP, MySQL and jQuery Ajax

In the web development world, user engagement and feedback are very important. Providing users with the ability to rate content not only fosters interaction but also offers valuable insights into the quality of your offerings.

In this comprehensive tutorial, we’ll explore how to implement a dynamic 5-star rating system using PHP 8, MySQL, and jQuery AJAX integration. Whether you’re building a blog, an e-commerce platform, or a review site, this rating system will add a layer of interactivity that users appreciate.

Understanding the Components

Before diving into the code, let’s break down the components involved:

Frontend Interface:

This is where users interact with the rating system. We’ll use HTML, CSS, and jQuery to create a visually appealing interface that allows users to select their desired rating.

Backend Logic:

PHP will handle the backend logic, including storing ratings in a MySQL database, retrieving average ratings, and updating them dynamically without page reloads.

Database Management:

MySQL will serve as our database management system to store user ratings and associated data.

Create a MySQL Database and Table

First, let’s create a MySQL database to store data. To create a MySQL database, go to phpMyAdmin dashboard from your localhost or cPanel interface. Then click on the “Databases” tab, enter the database name, and click on the Create button.

After creating a database, we’ll need a table to store ratings along with other relevant data, such as the item being rated and the user who submitted the rating.

Here’s a simple SQL schema to get us started.

CREATE TABLE ratings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    item_id INT NOT NULL,
    user_id INT NOT NULL,
    rating INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This SQL statement creates a table named “ratings” with columns for ID (automatically incrementing), item ID, user ID, rating, and creation timestamp. It ensures that item ID, user ID, and rating are not left empty.

The “created_at” column defaults to the current timestamp if not specified during insertion. This table structure is designed to store user ratings for different items along with relevant metadata.

Building the Frontend Interface

Now, let’s focus on the front end. We’ll create a simple HTML structure with five clickable stars representing the rating scale. We’ll enhance it with CSS for styling and jQuery for interactivity.

item.php

<div class="star-rating">
    <input type="radio" id="star5" name="rating" value="5"><label for="star5"></label>
    <input type="radio" id="star4" name="rating" value="4"><label for="star4"></label>
    <input type="radio" id="star3" name="rating" value="3"><label for="star3"></label>
    <input type="radio" id="star2" name="rating" value="2"><label for="star2"></label>
    <input type="radio" id="star1" name="rating" value="1"><label for="star1"></label>
</div>
.star-rating {
    display: flex;
  	flex-direction: row-reverse;
  	justify-content: center;
    font-size: 0; /* Remove whitespace between inline-block elements */
}

.star-rating input[type="radio"] {
    display: none; /* Hide the radio buttons */
}

.star-rating label {
    font-size: 30px;
    color: #ccc;
    cursor: pointer;
}

.star-rating label:before {
    content: "\2605"; /* Unicode character for a star */
}

.star-rating input[type="radio"]:checked ~ label {
    color: #ffcc00; /* Color the selected stars */
}

The above HTML and CSS code will result in the 5-stars and you can click it to change the rating. However, the functionality is not completed yet to save the rating. The output of the above code is shown in the following images.

5 star PHP HTML CSS

Setup MySQL Connection

Let’s create a separate file for MySQL connection to keep our code modular and organized. This file will handle the database connection and provide functions to interact with the database.

db_connection.php

<?php
$host = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

$connection = mysqli_connect($host, $username, $password, $database);

if ($connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>

Don’t forget to replace the values of localhost, username, password, and database with yours.

Implementing the Backend Logic with PHP

Next, let’s handle the backend logic using PHP. We’ll create endpoints to handle rating submission and retrieval requests. Here’s a simplified version of how we can handle rating submissions.

submit_rating.php

include "db_connection.php";
  
// Handle rating submission
if (isset($_POST['item_id'], $_POST['user_id'], $_POST['rating'])) {
    $item_id = $_POST['item_id'];
    $user_id = $_POST['user_id'];
    $rating = $_POST['rating'];

    // Insert rating into database
    $sql = "INSERT INTO ratings (item_id, user_id, rating) VALUES ('$item_id', '$user_id', '$rating')";
    if (mysqli_query($connection, $sql)) {
        echo "Rating submitted successfully.";
    } else {
        echo "ERROR: Could not execute $sql. " . mysqli_error($connection);
    }
}

In this above code, firstly, we included the database connection file to create a connection. Next, we checked that all the required $_POST variables were submitted and then we ran the MySQL INSERT query using the mysqli_query() function to insert the rating in the “rating” table.

Enhancing Interactivity with jQuery AJAX

To provide a seamless user experience, we’ll use jQuery AJAX to handle rating submissions without refreshing the page. Here’s a basic example of how we can achieve this.

submit_rating.js

// submit_rating.js
$(document).ready(function() {
    $(document).on('click', '.star-rating label', function() {
        var rating = $(this).prev('input[type="radio"]').val();
        var item_id = 1; // Replace with the ID of the item being rated
        var user_id = 1; // Replace with the ID of the current user

        $.ajax({
            url: 'submit_rating.php',
            method: 'POST',
            data: { item_id: item_id, user_id: user_id, rating: rating },
            success: function(response) {
                $('.rating-result').html(response);
            }
        });
    });
});

In the above code, we have added the click event on the label tag, when users click on it, it will get the value of the input tag using the prev() method.

Next, we made the Ajax request with the POST method to submit the data to the submit_rating.php file.

Display Average Rating

To display the average rating, we will modify the item.php file or wherever you want to display the 5-star rating system. First, we will calculate the rating using the MySQL AVG() method and then round and show it. See the following example code.

include 'db_connection.php';

function get_average_rating($item_id) {

    $sql = "SELECT AVG(rating) AS average_rating FROM ratings WHERE item_id = '$item_id'";
    $result = mysqli_query($connection, $sql);
    $row = mysqli_fetch_assoc($result);

    return round($row['average_rating'], 1);
}

This above code, you can keep as a separate file and then include it wherever you want or you can directly add this code into the item.php file to display the rating. Then call the get_average_rating() function in the HTML tag where you want to display the rating.

<div class="average-rating">
    <?php echo "Average Rating: " . get_average_rating($item_id); ?>
</div>

Conclusion

In this tutorial, we’ve explored how to create a dynamic 5-star rating system using PHP 8, MySQL, and jQuery AJAX integration. By providing users with the ability to rate content and display average ratings, you can enhance user engagement and gather valuable feedback. Whether you’re building a blog, an e-commerce platform, or a review site, implementing a rating system is a simple yet effective way to enrich the user experience.

Start integrating this rating system into your projects today and watch as user interaction and feedback propel your platform to new heights!

FAQs

What is a PHP 5-star rating system?

A PHP 5-star rating system is a feature on websites that allows users to rate content or products using a 5-star scale, providing quick feedback on their experience.

How does a PHP star rating system work?

A PHP star rating system typically involves frontend elements like clickable stars for users to select their rating. PHP handles backend logic, storing ratings in a database and calculating averages. AJAX is often used for seamless submission without page reloads.

Can I integrate a star rating system into my website?

Yes, you can integrate a star rating system into your website with PHP, MySQL, and JavaScript libraries like jQuery. It’s a user-friendly way to gather feedback and engage visitors.

Is a PHP star rating system customizable?

Absolutely! You can customize a PHP star rating system to match your website’s design and requirements. You can adjust star appearance, implement user authentication, and tailor the rating logic to suit your needs.

Is a PHP star rating system mobile-friendly?

Yes, a PHP star rating system can be made mobile-friendly by ensuring responsive design and touch-friendly interactions. Users can easily rate content on mobile devices, enhancing the user experience across all platforms.

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment