Please Rate the product:

Please Rate the product:

search
HomeBackend DevelopmentPHP ProblemHow to implement five-pointed star comments in PHP (steps)

Today, we will learn how to use PHP to implement a five-pointed star comment system. This system is typically used to allow users to rate a product, article or service and display the average score.

Step 1: Create an HTML form

We first need to create an HTML form that lets users select items to rate and give them a score:


 

请对产品进行评分:

 1分  2分  3分  4分  5分  
 

Step 2: Processing form data

In the submit.php file, we need to process the form data submitted by the user and store them in the database. First, we will check if the user has selected a rating item and display an error message if not.

Next, we will create a database connection and perform an INSERT query to add the rating data to the database. We will also calculate the average of all ratings and store it in another database table.

<?php  if(empty($_POST[&#39;rating&#39;])) {
   echo "请选择评分项";
 } else {
   $rating = $_POST[&#39;rating&#39;];
   $conn = mysqli_connect("localhost", "username", "password", "database");
   $query = "INSERT INTO ratings (rating) VALUES (&#39;$rating&#39;)";
   mysqli_query($conn, $query);

   $avg_query = "SELECT AVG(rating) as average FROM ratings";
   $result = mysqli_query($conn, $avg_query);
   $row = mysqli_fetch_assoc($result);
   $average = $row[&#39;average&#39;];

   $avg_insert = "INSERT INTO average_rating (average) VALUES ($average)";
   mysqli_query($conn, $avg_insert);

   echo "感谢您的评分!";
 }
?>

Step 3: Display the average score

Finally, we will display the average of all ratings to the user. We will retrieve this value from the database and display it on the web page.

<?php  $conn = mysqli_connect("localhost", "username", "password", "database");
 $avg_query = "SELECT AVG(average) as average FROM average_rating";
 $result = mysqli_query($conn, $avg_query);
 $row = mysqli_fetch_assoc($result);
 $average = round($row[&#39;average&#39;], 1);
?>

<p>平均得分: <?php  echo $average ?>/5</p>

Step 4: Implement the five-pointed star rating

Now, we have been able to collect and display the ratings, but we want to provide a better visual experience to the user. Therefore, we will use a five-pointed star instead of the original radio button.

To do this, we will use HTML, CSS, and JavaScript to create the five-pointed star, and PHP to process the user-submitted form data. We'll use CSS to make the five-pointed star gray, and use JavaScript to color the star yellow when the user hovers over it.

<style>
 .unchecked {
   color: grey;
 }
 .checked {
   color: yellow;
   cursor: pointer;
 }
</style>

<span>
 <?php    for($i = 1; $i <= 5; $i++) {
     echo "<i class=&#39;fa fa-star&#39; data-value=&#39;$i&#39;>";
   }
 ?>
</span>

<script>
 function rate(element) {
   var stars = element.getElementsByTagName("i");
   for(var i = 0; i < stars.length; i++) {
     stars[i].classList.remove("checked");
     stars[i].classList.add("unchecked");
   }

   var clicked = event.target.dataset.value;
   for(var i = 0; i < clicked; i++) {
     stars[i].classList.remove("unchecked");
     stars[i].classList.add("checked");
   }

   document.querySelector("input[name=&#39;rating&#39;]").value = clicked;
 }
</script>

Now when the user hovers over the stars, they will be colored yellow and the corresponding rating value will be put into the form data.

Finally, we replace the radio buttons in the code for PHP submission handling with hidden form inputs. The input will be automatically populated in JavaScript.

<span>
 <?php    for($i = 1; $i <= 5; $i++) {
     echo "<i class=&#39;fa fa-star&#39; data-value=&#39;$i&#39;>";
   }
 ?>
</span>

<input>

Here we can set the name of the radio button to "rating" and set the "required" attribute on it to ensure that the user selects an item.

We have now successfully implemented a five-pointed star review system that allows users to associate ratings with a website, product, or article and display the average score to other users. This system is a simple yet useful interactive feature that improves user experience and helps website owners better understand their audience.

The above is the detailed content of How to implement five-pointed star comments in PHP (steps). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Use Asynchronous Tasks in PHP for Non-Blocking Operations?How to Use Asynchronous Tasks in PHP for Non-Blocking Operations?Mar 10, 2025 pm 04:21 PM

This article explores asynchronous task execution in PHP to enhance web application responsiveness. It details methods like message queues, asynchronous frameworks (ReactPHP, Swoole), and background processes, emphasizing best practices for efficien

How to Implement message queues (RabbitMQ, Redis) in PHP?How to Implement message queues (RabbitMQ, Redis) in PHP?Mar 10, 2025 pm 06:15 PM

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

What Are the Latest PHP Coding Standards and Best Practices?What Are the Latest PHP Coding Standards and Best Practices?Mar 10, 2025 pm 06:16 PM

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

How to Use Reflection to Analyze and Manipulate PHP Code?How to Use Reflection to Analyze and Manipulate PHP Code?Mar 10, 2025 pm 06:12 PM

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea

How Do I Work with PHP Extensions and PECL?How Do I Work with PHP Extensions and PECL?Mar 10, 2025 pm 06:12 PM

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance.PHP 8 JIT (Just-In-Time) Compilation: How it improves performance.Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

How to Use Memory Optimization Techniques in PHP?How to Use Memory Optimization Techniques in PHP?Mar 10, 2025 pm 04:23 PM

This article addresses PHP memory optimization. It details techniques like using appropriate data structures, avoiding unnecessary object creation, and employing efficient algorithms. Common memory leak sources (e.g., unclosed connections, global v

How Do I Stay Up-to-Date with the PHP Ecosystem and Community?How Do I Stay Up-to-Date with the PHP Ecosystem and Community?Mar 10, 2025 pm 06:16 PM

This article explores strategies for staying current in the PHP ecosystem. It emphasizes utilizing official channels, community forums, conferences, and open-source contributions. The author highlights best resources for learning new features and a

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools