The simplest code for Star ratings
Tweet
What you need:
- PHP with MySQL/MariaDB
- jQuery
- FontAwesome
Rating
<?php
/*
Author : M.H.E. Vos
Copyright : (c) 2024, SDS82
Creation date : 2024-01-01
*/
print('<style>
.reviewing
{
cursor: pointer;
}
.reviewing .fa-star.checked
{
color: orange;
}
</style>');
$theorder = 1234;
if ($iresult = mysqli_query($db_connection, "select * from orderitems where orderid = '$theorder'"))
{
while ($thisitem = $iresult->fetch_object())
{
$rating = 0;
$alreadyrated = 0;
if ($rresult = mysqli_query($db_connection, "select rating from ratings where orderid = '$theorder' and productid = '" . addslashes(thisitem->itemid) . "'"))
{
while ($obj = $rresult->fetch_object())
{
$rating = intval($obj->rating);
$alreadyrated = 1;
}
mysqli_free_result($rresult);
}
// Display rating
print('<div class="reviewing">
<span class="fa fa-star ' . ($alreadyrated ? ($rating >= 1 ? 'checked' : '') : 'notrated') . '" aria-hidden="true" data-value="1" data-sku="' . $thisitem->itemid . '"></span>
<span class="fa fa-star ' . ($alreadyrated ? ($rating >= 2 ? 'checked' : '') : 'notrated') . '" aria-hidden="true" data-value="2" data-sku="' . $thisitem->itemid . '"></span>
<span class="fa fa-star ' . ($alreadyrated ? ($rating >= 3 ? 'checked' : '') : 'notrated') . '" aria-hidden="true" data-value="3" data-sku="' . $thisitem->itemid . '"></span>
<span class="fa fa-star ' . ($alreadyrated ? ($rating >= 4 ? 'checked' : '') : 'notrated') . '" aria-hidden="true" data-value="4" data-sku="' . $thisitem->itemid . '"></span>
<span class="fa fa-star ' . ($alreadyrated ? ($rating >= 5 ? 'checked' : '') : 'notrated') . '" aria-hidden="true" data-value="5" data-sku="' . $thisitem->itemid . '"></span>
' . (!$alreadyrated ? '<input form="yourform" id="R' . $thisitem->itemid . '" name="R' . $thisitem->itemid . '" type="hidden" value="' . $rating . '">' : '') . '
</div>');
}
mysqli_free_result($oresult);
}
print('<script>
$(document).ready(function() {
$(".reviewing .fa-star.notrated").hover(function() {
$(this).parent().children(".fa-star").removeClass("checked");
$(this).addClass("checked").prevAll(".fa-star").addClass("checked");
$("#R" + $(this).data("sku")).val($(this).data("value"));
});
});
</script>');
?>
You can add AJAX code to store the rating or add a submit button to submit the 'yourform' form and store the rating that way.
You can also change 'hover' into 'clicked' when you want your customers to actually click on a star.
That's it! Happy coding!