Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 13, 2023 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/5d319b2f896e4dd17f5e67cd7bcb3069 to your computer and use it in GitHub Desktop.
Save code-boxx/5d319b2f896e4dd17f5e67cd7bcb3069 to your computer and use it in GitHub Desktop.
PHP MYSQL Star Rating System

STAR RATING SYSTEM WITH PHP MYSQL

https://code-boxx.com/php-star-rating/

IMAGES

burger stars

NOTES

  1. Create a database and import 1-database.sql.
  2. Change the database settings in 2-lib.php to your own.
  3. Launch 3a-products.php in your browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `star_rating` (
`product_id` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`rating` smallint(6) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `star_rating`
ADD PRIMARY KEY (`product_id`,`user_id`);
INSERT INTO `star_rating` (`product_id`, `user_id`, `rating`) VALUES
(1, 900, 1),
(1, 901, 2),
(1, 902, 5),
(2, 901, 3),
(2, 902, 4),
(2, 903, 5),
(2, 904, 2);
<?php
class Stars {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo;
private $stmt;
public $error;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) HELPER - RUN SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) SAVE/UPDATE USER STAR RATING
function save ($pid, $uid, $stars) {
$this->query(
"REPLACE INTO `star_rating` (`product_id`, `user_id`, `rating`) VALUES (?,?,?)",
[$pid, $uid, $stars]
);
return true;
}
// (E) GET USER STAR RATINGS
function get ($uid) {
$this->query("SELECT * FROM `star_rating` WHERE `user_id`=?", [$uid]);
$star = [];
while ($r = $this->stmt->fetch()) { $star[$r["product_id"]] = $r["rating"]; }
return $star;
}
// (F) GET AVERAGE STAR RATING
function avg () {
$this->query(
"SELECT `product_id`, ROUND(AVG(`rating`), 2) `avg`, COUNT(`user_id`) `num`
FROM `star_rating` GROUP BY `product_id`"
);
$average = [];
while ($r = $this->stmt->fetch()) {
$average[$r["product_id"]] = [
"avg" => $r["avg"], // average rating
"num" => $r["num"] // number of reviews
];
}
return $average;
}
}
// (G) DATABASE SETTINGS - CHANGE TO YOUR OWN !
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (H) NEW STARS OBJECT
$_STARS = new Stars();
<!DOCTYPE html>
<html>
<head>
<title>DUMMY PRODUCTS PAGE</title>
<meta charset="utf-8">
<script src="3b-products.js"></script>
<link rel="stylesheet" href="3c-products.css">
</head>
<body>
<?php
// (A) CORE LIBRARY + USER ID
require "2-lib.php";
$uid = 901; // fixed for demo, use your own session user id
// (B) UPDATE STAR RATINGS
if (isset($_POST["pid"]) && isset($_POST["stars"])) {
echo $_STARS->save($_POST["pid"], $uid, $_POST["stars"])
? "<div class='note'>Rating Saved</div>" : "<div class='note'>Error</div>" ;
}
?>
<div id="demo"><?php
// (C) GET RATINGS
$average = $_STARS->avg(); // average ratings
$ratings = $_STARS->get($uid); // ratings by current user
// (D) OUTPUT DUMMY PRODUCTS
$products = [1 => "Hamburger", 2 => "Humborgar"];
foreach ($products as $pid=>$pdt) { ?>
<div class="pCell">
<img class="pImg" src="burger.png">
<div class="pName"><?=$pdt?></div>
<div class="pReview">Customer Reviews</div>
<div class="pStar" data-pid="<?=$pid?>"><?php
$rate = isset($ratings[$pid]) ? $ratings[$pid] : 0 ;
for ($i=1; $i<=5; $i++) {
$css = $i<=$rate ? "star" : "star blank" ;
echo "<div class='$css' data-i='$i'></div>";
}
?></div>
<div class="pStat">
<?=$average[$pid]["avg"]?> out of 5 stars.
</div>
<div class="pStat">
<?=$average[$pid]["num"]?> customer ratings.
</div>
</div>
<?php }
?></div>
<!-- (E) HIDDEN FORM TO UPDATE STAR RATING -->
<form id="ninForm" method="post" target="_self">
<input id="ninPdt" type="hidden" name="pid">
<input id="ninStar" type="hidden" name="stars">
</form>
</body>
</html>
var stars = {
// (A) INIT - ATTACH HOVER & CLICK EVENTS
init : () => {
for (let d of document.querySelectorAll(".pStar")) {
let all = d.querySelectorAll(".star");
for (let s of all) {
s.onmouseover = () => stars.hover(all, s.dataset.i);
s.onclick = () => stars.click(d.dataset.pid, s.dataset.i);
}
}
},
// (B) HOVER - UPDATE NUMBER OF YELLOW STARS
hover : (all, rating) => {
let now = 1;
for (let s of all) {
if (now<=rating) { s.classList.remove("blank"); }
else { s.classList.add("blank"); }
now++;
}
},
// (C) CLICK - SUBMIT FORM
click : (pid, rating) => {
document.getElementById("ninPdt").value = pid;
document.getElementById("ninStar").value = rating;
document.getElementById("ninForm").submit();
}
};
window.addEventListener("load", stars.init);
/* (A) WHOLE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
max-width: 600px;
padding: 10px;
margin: 0 auto;
background: #f2f2f2;
}
.note {
padding: 10px;
margin-bottom: 10px;
border: 1px solid #f5e9ad;
background: #fff8e2;
}
/* (B) PRODUCTS LIST */
#demo {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-gap: 10px;
}
.pCell {
padding: 20px;
background: #fff;
border: 1px solid #ecede7;
}
.pImg {
display: block;
width: 100%;
}
.pName {
font-size: 24px;
margin-top: 10px;
}
.pReview { color: #fb3232; }
.pStar {
display: flex;
margin-bottom: 15px;
}
.pStar .star {
width: 36px;
height: 36px;
background-image: url("stars.png");
cursor: pointer;
}
.pStar .star.blank { background-position: -36px; }
.pStat {
font-size: 15px;
color: #4a4a4a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment