5 star rating system php code

This example will use a simple 5-star rating system. Here's a basic outline of how you can implement it:


1. **Create a Database Table:**

   First, create a database table to store ratings. You'll need columns for the user's ID, item ID (if you're rating specific items), and the rating value.


   ```sql

   CREATE TABLE ratings (

       id INT AUTO_INCREMENT PRIMARY KEY,

       user_id INT,

       item_id INT,

       rating INT

   );

   ```


2. **Display Ratings:**

   On the webpage where you want to display ratings, you can retrieve the average rating for an item and show it. Here's a simplified example:


   ```php

   <?php

   // Connect to your database (not shown here)


   $item_id = 1; // Replace with your item's ID

   $query = "SELECT AVG(rating) AS average_rating FROM ratings WHERE item_id = $item_id";

   $result = mysqli_query($conn, $query);

   $row = mysqli_fetch_assoc($result);


   if ($row['average_rating'] !== null) {

       echo "Average Rating: " . number_format($row['average_rating'], 2);

   } else {

       echo "No ratings yet.";

   }

   ?>

   ```


3. **Allow Users to Rate:**

   Provide a way for users to submit ratings. You can use a simple form for this. Here's an example of a form:


   ```html

   <form action="submit_rating.php" method="POST">

       <input type="hidden" name="item_id" value="1"> <!-- Replace with your item's ID -->

       <select name="rating">

           <option value="1">1 Star</option>

           <option value="2">2 Stars</option>

           <option value="3">3 Stars</option>

           <option value="4">4 Stars</option>

           <option value="5">5 Stars</option>

       </select>

       <input type="submit" value="Submit Rating">

   </form>

   ```


4. **Submit Rating:**

   Create a PHP script (`submit_rating.php`) to handle the form submission and insert the user's rating into the database:


   ```php

   <?php

   // Connect to your database (not shown here)


   $user_id = 1; // Replace with the actual user's ID

   $item_id = $_POST['item_id'];

   $rating = $_POST['rating'];


   $query = "INSERT INTO ratings (user_id, item_id, rating) VALUES ($user_id, $item_id, $rating)";

   mysqli_query($conn, $query);


   // Redirect the user back to the item page or show a thank you message

   ?>

   ```


This is a basic example to get you started. You can enhance and customize it to fit your website's needs. Additionally, make sure to handle security measures such as input validation and preventing SQL injection in a production environment.

Previous
Next Post »