Build PHP MySQL 5 Star Rating System Using jQuery AJAX Example

PHP 8 , PHP

Nicesnippets

1128

09-08-2021


Build PHP MySQL 5 Star Rating System Using jQuery AJAX Example

Hi guys,

Today i will explained How to build php rating system using php ,jquery and ajax. This example is so easy to use in php.

Furthermore, we will also explain how to store star rating value in the MySQL database through AJAX request. Additionally, this value will keep on changing if the user updates the ratings.

This example to i will use in jQuery bar plugin into the PHP so you can dowload plugin download the jQuery Bar Rating so please follow to the my all step.

Then, you require to create an assets folder and unzip the bar rating package inside the assets/jquery-bar-rating-master directory.

So let's start to the example.

create a database


We can execute SQL queries to create products table and product_rating tables.

CREATE TABLE `products` (

`id` int(11) NOT NULL,

`name` varchar(100) NOT NULL,

`description` text NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO products VALUES (1, 'New Balance CK4040 V5', 'Phasellus at scelerisque eros, elementum congue leo.');

INSERT INTO products VALUES (2, 'SS Players Series - Chest Guard', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.');

INSERT INTO products VALUES (3, "Shrey Supporters - TRUNK", "Ut ultrices nibh non orci sollicitudin.");

INSERT INTO products VALUES (4, "New Balance - Batting Inners", "Sed sed magna consequat, cursus felis.");

INSERT INTO products VALUES (5, "Gray-Nicolls TEST Arm Guard", "Etiam vulputate condimentum facilisis.");

INSERT INTO products VALUES (6, "SS Ton Vintage MSD 4.0 - Cricket Bat", "Aliquam nec tortor porttitor, mollis quam sit amet.");

INSERT INTO products VALUES (7, "Shrey Pro Guard - Titanium", "Vivamus lacinia augue id ipsum luctus molestie.");

CREATE TABLE `product_rating` (

`id` int(11) NOT NULL,

`user_id` int(11) NOT NULL,

`product_id` int(11) NOT NULL,

`rating` int(2) NOT NULL,

`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

PHP MySQL Server Connection

To make the PHP and MySQL database connection, update the database/db.php file:

<?php

$connection = mysqli_connect('localhost','root','root','php') or die('Unable To connect');

?>

show_star_ratings.php

This file to make your project root folder.

<?php

$user_id = 1;

$query = "SELECT * FROM products";

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

while($row = mysqli_fetch_array($result)){

$product_id = $row['id'];

$name = $row['name'];

$description = $row['description'];

// Star rating

$query = "SELECT * FROM product_rating WHERE product_id = " . $product_id . " and user_id = " . $user_id;

$productResult = mysqli_query($connection, $query);

$getRating = mysqli_fetch_array($productResult);

$rating = $getRating['rating'];

// Rating

$query = "SELECT ROUND(AVG(rating), 1) as numRating FROM product_rating WHERE product_id=".$product_id;

$avgresult = mysqli_query($connection, $query);

$fetchAverage = mysqli_fetch_array($avgresult);

$numRating = $fetchAverage['numRating'];

if($numRating <= 0){

$numRating = "Not ratings given.";

}

?>

<div class="card mb-3">

<div class="card-body">

<h2 class="card-title"><?php echo $name; ?></h2>

<p class="card-text">

<?php echo $description; ?>

</p>

<select name="star_rating_option" class="rating" id='star_rating_<?php echo $product_id; ?>'

data-id='rating_<?php echo $product_id; ?>'>

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

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

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

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

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

</select>

Rating : <span id='numeric_rating_<?php echo $product_id; ?>'><?php echo $numRating; ?></span>

</div>

</div>

<?php } ?>

ajax_star_rating.php

This file to make your project root folder.

include "./database/db.php";

$user_id = 1;

$product_id = $_POST['product_id'];

$rating = $_POST['rating'];

// Check rating inside the table

$query = "SELECT COUNT(*) AS countProduct FROM product_rating WHERE product_id = " . $product_id . " and user_id = " . $user_id;

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

$getdata = mysqli_fetch_array($result);

$count = $getdata['countProduct'];

if($count == 0){

$insertquery = "INSERT INTO product_rating(user_id, product_id, rating) values(". $user_id .", ". $product_id .", ". $rating .")";

mysqli_query($connection, $insertquery);

}else {

$updateRating = "UPDATE product_rating SET rating=" . $rating . " where user_id=" . $user_id . " and product_id=" . $product_id;

mysqli_query($connection, $updateRating);

}

// fetch rating

$query = "SELECT ROUND(AVG(rating),1) as numRating FROM product_rating WHERE product_id=".$product_id;

$result = mysqli_query($connection, $query) or die(mysqli_error());

$getAverage = mysqli_fetch_array($result);

$numRating = $getAverage['numRating'];

$return_arr = array("numRating"=>$numRating);

echo json_encode($return_arr);

index.php

This file to make your project root folder.

<?php include "./database/db.php"; ?>

<html>

<head>

<title>Build PHP MySQL 5 Star Rating System Using jQuery AJAX Example - Nicesnippets.com</title>

<link href="https://cdn.jsdelivr.net/npm/[email protected]0-beta3/dist/css/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">

<link href='./assets/jquery-bar-rating-master/dist/themes/fontawesome-stars.css' rel='stylesheet' type='text/css'>

<link href="./styles.css" type="text/css" rel="stylesheet" />

</head>

<body>

<div class="content container mt-5">

<?php include "./show_star_ratings.php"; ?>

</div>

</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script src="./assets/jquery-bar-rating-master/dist/jquery.barrating.min.js"></script>

<script type='text/javascript'>

$(document).ready(function(){

$('#star_rating_<?php echo $product_id; ?>').barrating('set',<?php echo $rating; ?>);

});

$(function () {

$('.rating').barrating({

theme: 'fontawesome-stars',

onSelect: function (value, text, event) {

var el = this;

var el_id = el.$elem.data('id');

if (typeof (event) !== 'undefined') {

var split_id = el_id.split("_");

var product_id = split_id[1];

$.ajax({

url: './ajax_star_rating.php',

type: 'post',

data: {

product_id: product_id,

rating: value

},

dataType: 'json',

success: function (data) {

var average = data['numRating'];

$('#numeric_rating_' + product_id).text(average);

}

});

}

}

});

});

</script>

</html>

Now you can check your own.

I hope it can help you...


Recommended Posts