etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Simple star rating system using PHP, jQuery and Ajax

In this tutorial, you will learn how to rate the listed products using PHP, jQuery and Ajax. Today, star rating system is mostly used in eCommerce to rate the products, service rating, organization rating, article rating, etc. It helps the seller to improve their service based on the star rating provided by the customers. It also helps the other customers to choose the right products.

In this article, we have listed some products for rating. For this, we have created a MySQL table and inserted some products with rating in database. You can use the records if you already have, otherwise you can create it manually or copy and paste the following queries in your database.

CREATE TABLE IF NOT EXISTS `product_rating` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product` varchar(100) DEFAULT NULL,
  `rating` int(11) NOT NULL,
  PRIMARY KEY (`id`)
); 


INSERT INTO `product_rating` (`id`, `product`, `rating`) VALUES
(1, 'Product 1', 3),
(2, 'Product 2', 4),
(3, 'Product 3', 4),
(4, 'Product 4', 1);




Simple star rating system using PHP, jQuery and Ajax

In this article, we have created two PHP files- 'rating.php' and 'index.php'.

The 'rating.php' file contains code for the database connection. Here, we have created a class 'Rating' using PHP and written the PHP MySQLi database connection code in the constructor. The select() and update() functions are used to select the data and for update the product rating respectively. The update function dynamically calls to update the product rating using Ajax. At the top of this PHP file, we get the 'functionName' value in GET which is provided by the 'index.php' file. If it is 'update' then, it dynamically calls the update() function and updates the product rating.

Make sure to replace the host, username, password and database with your database credentials and database name.





rating.php

<?php
$functionName = $_GET['functionName'];
if($functionName == "update") {
$getFunc = new Rating();
echo $getFunc->update($_GET['proid'], $_GET['rating']);
} 

class Rating {
// Database credentials
private $host     = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'demo';
public  $db;

public function __construct(){
if(!isset($this->db)){
	// Connect to the database    
	try {
	$this->db = new mysqli($this->host, $this->username, $this->password, $this->database);
	}catch (Exception $e){
	$error = $e->getMessage();
	echo $error;
	}
}
}
public function select(){
$select = "SELECT * FROM `product_rating` ";
$result = mysqli_query($this->db ,$select);
return mysqli_fetch_all($result);
}
public function update($id, $rating) {
$update = "UPDATE `product_rating` SET rating = '$rating' WHERE id = '$id' ";
$result = mysqli_query($this->db ,$update);
if($result) { 
	return 'Data Updated Successfully';
}
} 
}
?>

The 'index.php' is the main file, that we will call on the browser. In this file, the product list with their ratings are arranged in HTML table. These data are fetched by the select() function. That's why, we have included the 'rating.php' file and instantiate the 'Rating' class

To dynamically update the product ratings, we have written the Ajax code in ratestar() function. So if the user clicks on the rating star, a javascript function ratestar() will be called and it dynamically updates the current product's rating on the database.





index.php

<!DOCTYPE html>
<html>
<head>
<title>Simple star rating system using PHP, jQuery and Ajax</title>
<style type="text/css">
	.star_rated { color: gold; }
	.star {text-shadow: 0 0 1px #F48F0A; cursor: pointer;  }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function ratestar($id, $rate){
	$.ajax({
		type: 'GET',
		url: 'rating.php',
		data: 'functionName=update&productid='+$id+'&rating='+$rate,
		success: function(data) { 
			location.reload();
		}
	});
}
</script>
</head>
<body>
<?php
	include 'rating.php';
	$db = new Rating();
	$data = $db->select();
?>
<table>
<thead>
<th>Product</th>
<th>Rating</th>
</thead>
<?php
foreach($data as $pro) {
?>
<tr>
	<td><?php echo $pro[1]; ?></td>
	<td>
    <div class="star">
	<?php
	for($i = 1; $i <= 5; $i++) {
	if($i <= $pro[2]) {
	?>
	<span class="star_rated" onclick="ratestar(<?php echo $pro[0]; ?>, <?php echo $i; ?>)">&#x2605;</span>
	<?php }  else {  ?>
	<span onclick="ratestar(<?php echo $pro[0]; ?>, <?php echo $i; ?>)">&#x2605;</span>
	<?php  }
	}
	?>
	</div>
	</td>
</tr>
<?php
}
?>
</table>        
</body>
</html>




Related Articles

How to prevent CSRF attack in PHP
PHP contact form send email SMTP
Dynamic pagination in PHP
PHP cache data in memory
PHP Connection and File Handling on FTP Server
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
JavaScript display PDF in the browser using Ajax call
How to Retrieve Emails from Gmail using PHP IMAP
How to store Emoji character in MySQL using PHP
How to display PDF file in PHP from database
jQuery loop over JSON result after AJAX Success




Most Popular Development Resources
Characteristics of a Good Computer Program
-----------------
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
How to get data from XML file in PHP
-----------------
PHP code to send email using SMTP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP Create Word Document from HTML
-----------------
How to encrypt password in PHP
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Simple pagination in PHP with MySQL
-----------------
Fibonacci Series Program in PHP
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
How to add multiple custom markers on google map
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
Php file based authentication
-----------------
jQuery File upload progress bar with file size validation
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple PHP File Cache
-----------------
Polling system using PHP, Ajax and MySql
-----------------
SQL Injection Prevention Techniques
-----------------
Simple File Upload Script in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
PHP User Authentication by IP Address
-----------------
How to generate QR Code in PHP
-----------------
Calculate the distance between two locations using PHP
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Detect Mobile Devices in PHP
-----------------
Set and Get Cookies in PHP
-----------------
PHP Server Side Form Validation
-----------------
To check whether a year is a leap year or not in php
-----------------
Date Timestamp Formats in PHP
-----------------
Get Visitor\'s location and TimeZone
-----------------
Convert MySQL to JSON using PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
PHP Programming Error Types
-----------------
PHP Sending HTML form data to an Email
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
How to print specific part of a web page in javascript
-----------------
Google Street View API Example
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
PHP Getting Document of Remote Address
-----------------
PHP Connection and File Handling on FTP Server
-----------------
File Upload Validation in PHP
-----------------
R Plot Types
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 27

    Best AI Startups In India

    Artificial Intelligence is a process of making an intelligent computer machine that does tasks intelligently...

  • Jan 23

    Most in demand programming languages for 2019

    In this article, we have mentioned the analyzed results of the most in demand programming language for 2019...

  • Jan 15

    Web Robots

    Web robots is an internet robot or simply crawlers, or spiders and do not relate this with hardware robots...

  • Jan 12

    Most in demand NoSQL databases software for 2019

    In this article, we have mentioned the analyzed result of most in demand NoSQL database softwares for 2019...

  • Jan 10

    Kotlin : Android App Development Choice

    Kotlin is a general-purpose open-source programming language. It runs on the JVM and its syntax is much like Java...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2021. All Rights Reserved.