Display Star Ratings from the Database in PHP and MySQL

Star ratings are widely used to display ratings, reviews, or feedback on a product or service. In this tutorial, you will learn how to display star ratings using PHP and MySQL. Our ratings are already stored in a database table and we will display them after retrieving them from the database.

We will use a simple example of hotel details stored in the database, including star ratings. Each hotel will have a rating field which is a number and can have values between 0 and 5. We also added '0' for not-rated hotels. Each number has a caption: 0 - Not Rated, 1- One Star, 2 - Two Star, 3 - Three Star, 4 - Four Star, 5 - Five Star.

We will display the details of the hotels in an html table and in this table, there will be a column for rating. In the rating field, we will display stars and the caption for each rating with the appropriate color as shown below:

how to display star rating in php and mysql

Watch YouTube Video

We have created a folder called 'star_rating' under 'xampp/htdocs'. We will have a separate 'css' folder for our custom stylesheet. Our main program will be index.php to display a list of hotels with star ratings.

Create a MySQL table to store hotel details

We will create a table named 'hotels' in a MySQL database. The table structure is given below:

star rating example in PHP table structure

This table has 5 columns.

  1. id - Primary key and auto incremented
  2. hotel_name - Name of the hotel
  3. description - Description of the hotel
  4. rating - Rating of the hotel, it is an integer, values 0 - 5
  5. date_created - Default is current date

hotels.sql


CREATE TABLE `hotels` (
  `id` int(11) NOT NULL,
  `hotel_name` varchar(200) NOT NULL,
  `description` varchar(500) NOT NULL,
  `rating` tinyint(4) NOT NULL,
  `date_created` date NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci;

INSERT INTO `hotels` (`id`, `hotel_name`, `description`, `rating`, `date_created`) VALUES
(1, 'NJoyNEat', 'For your delicious foods and enjoy all kinds of ride', 4, '2021-12-01'),
(2, 'New Guest House', 'All kinds of modern facilities available with free Wi-Fi', 3, '2021-02-11'),
(3, 'Hotel Sonali', 'Sea facing rooms for your holiday leisures, now book online and get 10% discount', 2, '2021-12-01'),
(4, 'Hotel Express', 'New Hotel for all your modern amenities', 1, '2021-12-01'),
(5, 'Resort and Inn', 'Your perfect holiday stay', 5, '2021-12-01'),
(6, 'Holiday Home', 'Your dream hotels are here', 0, '2021-12-01');

ALTER TABLE `hotels`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `hotels`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

Display a list of hotels with star ratings (index.php)

The rating for each hotel will be displayed as a star symbol and depending on the rating, one or more star symbols will be highlighted. Also, a description of the rating will be displayed with a color code, for example, for "One Star" it will be red and for "Five Star" it will be green. If no rating is given, the default rating will be zero and it will denote Not-Rated as shown below:

how to display star rating in php and mysql

Let us now see the code for index.php

index.php


<!DOCTYPE html>
<html lang="en">

<head>
	<title>Star Rating</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
	<link rel="stylesheet" href="css/style.css">
</head>

<body>
	<?php
	// Connect to the database
	$conn = new mysqli("localhost", "root", "", "test");
	//Check connection
	if ($conn->connect_error)
		die("Connection Error: " . $conn->connect_error);

	$sql = "select * from hotels order by hotel_name";
	$stmt = $conn->prepare($sql);
	$stmt->execute();
	$result = $stmt->get_result();
	?>
	<div class="container">
		<h1>List of Hotels with Star Ratings</h1>
		<div class="table-responsive">
			<table class="table table-bordered table-striped">
				<thead class="table-dark">
					<tr>
						<th>Sr No.</th>
						<th>Hotel Name</th>
						<th>Description</th>
						<th>Rating</th>
					</tr>
				</thead>
				<tbody>
					<?php
					if ($result->num_rows > 0) { // if hotel exists
						$counter = 0;
						foreach ($result as $row) {
							$counter++;
							$star_rating = $row['rating'];
							switch ($star_rating) {
								case 0:
									$rating = "Not Rated";
									$label = "bg-secondary";
									break;
								case 1:
									$rating = "One Star";
									$label = "bg-danger";
									break;
								case 2:
									$rating = "Two Star";
									$label = "bg-warning";
									break;
								case 3:
									$rating = "Three Star";
									$label = "bg-info";
									break;
								case 4:
									$rating = "Four Star";
									$label = "bg-primary";
									break;
								case 5:
									$rating = "Five Star";
									$label = "bg-success";
									break;
								default:
									$rating = "Not Rated";
									$label = "bg-secondary";
							}
					?>
							<tr>
								<td><?= $counter . "."; ?></td>
								<td><?= $row["hotel_name"]; ?></td>
								<td><?= $row["description"]; ?></td>
								<td>
									<div class="rating">
										<ul>
											<?php
											for ($i = 1; $i <= 5; $i++) {
												if ($i <= $star_rating)
													$class = "selected";
												else
													$class = "";
											?>
												<li class="<?= $class ?>">&#9733;</li>
											<?php }
											?>

										</ul>
									</div>
									<span class="badge <?= $label ?>"><?= $rating; ?></span>
								</td>
							</tr>
						<?php
						}
					} else { ?>
						<tr>
							<td colspan="4">No Hotels Available to Display</td>
						</tr>
					<?php } ?>
				</tbody>
			</table>
		</div>
	</div>
</body>

</html>

We have a simple html table with three fields. We have an integer for rating, but we need to display stars and highlight the number of stars based on the rating value.

Using a for loop, star symbols are displayed. All stars with values less than or equal to the rating are being added with a class called 'selected'. This class is added in style.css and it is used to show the stars with the highlighted color. To display the star symbol, use code "&#9733;".

Add CSS (style.css)

Let us add the below styles. We have already added style.css in index.php.

style.css


*{
	box-sizing: border-box;
}
h1 {
	text-align: center;
}
.table{
	width: 80%;
	margin: auto;
	text-align: center;
}

.table li, .rating{
	display: inline-block;
	color: #aaa;
	text-shadow: 1px 1px 1px #666666;
	
}
.table .selected {
	color:#F4B30A;
	text-shadow: 1px 1px 1px #F48F0A;
}

You can see the class 'selected' is added along with other simple styles. Keep this style.css in your css folder.

iconTest the Application

Check that Apache and MySQL services are running in the XAMPP control panel. Run localhost/star_rating in the browser. You will see the below page displayed:

display dynamic star rating in php and mysql

You can see the stars are showing with color for specific ratings. If there is no rating, it means the rating is 0, then it displays “Not-Rated” and no stars are highlighted.

download source code to display star rating in php and mysqlDownload Source Code

You can download the source code by clicking on the Download button below.

how to display star rating in php and mysqlConclusion

In this tutorial, we have learned how to display the star ratings from the database in an html table. We used an example for the hotels; it can be the rating for a product or feedback as well. You can change it to meet your requirements using a similar structure and concept.

Please write your comments/questions in the Comments section below. Your questions, doubts and suggestions are always welcome.

Post a Comment

Save my Name and Email id for future comments