
In this PHP tutorial, we are going to list database records and add a dynamic star rating to those records by using jQuery star rating script. We are having a group of stars for each database record. When we add the rating to a record, an AJAX call will be sent store the current rating to the database.
This PHP code is for reading Database results and adding stars for each.
<?php require_once("Rate.php"); $rate = new Rate(); $result = $rate->getAllPost(); if(!empty($result)) { foreach ($result as $tutorial) { ?> <tr> <td valign="top"> <div class="feed_title"><?php echo $tutorial["title"]; ?></div> <div id="tutorial-<?php echo $tutorial["id"]; ?>"> <input type="hidden" name="rating" id="rating" value="<?php echo $tutorial["rating"]; ?>" /> <ul onMouseOut="resetRating(<?php echo $tutorial["id"]; ?>);"> <?php for($i=1;$i<=5;$i++) { $selected = ""; if(!empty($tutorial["rating"]) && $i<=$tutorial["rating"]) { $selected = "selected"; } ?> <li class='<?php echo $selected; ?>' onmouseover="highlightStar(this,<?php echo $tutorial["id"]; ?>);" onmouseout="removeHighlight(<?php echo $tutorial["id"]; ?>);" onClick="addRating(this,<?php echo $tutorial["id"]; ?>);">★</li> <?php } ?> <ul> </div> <div><?php echo $tutorial["description"]; ?></div> </td> </tr> <?php }} ?>
In this example code, we have same four jQuery functions. But, we have added additional code for calling PHP via AJAX on clicking rating stars. And also, we have added database row id reference to the “li” selectors for the unique identification of the rating. The functions are,
function highlightStar(obj,id) { removeHighlight(id); $('.demo-table #tutorial-'+id+' li').each(function(index) { $(this).addClass('highlight'); if(index == $('.demo-table #tutorial-'+id+' li').index(obj)) { return false; } }); } function removeHighlight(id) { $('.demo-table #tutorial-'+id+' li').removeClass('selected'); $('.demo-table #tutorial-'+id+' li').removeClass('highlight'); } function addRating(obj,id) { $('.demo-table #tutorial-'+id+' li').each(function(index) { $(this).addClass('selected'); $('#tutorial-'+id+' #rating').val((index+1)); if(index == $('.demo-table #tutorial-'+id+' li').index(obj)) { return false; } }); $.ajax({ url: "add_rating.php", data:'id='+id+'&rating='+$('#tutorial-'+id+' #rating').val(), type: "POST" }); } function resetRating(id) { if($('#tutorial-'+id+' #rating').val() != 0) { $('.demo-table #tutorial-'+id+' li').each(function(index) { $(this).addClass('selected'); if((index+1) == $('#tutorial-'+id+' #rating').val()) { return false; } }); } }
This PHP code will be executed via an AJAX request. This code runs an update query by receiving id and current rating from AJAX.
<?php if(!empty($_POST["rating"]) && !empty($_POST["id"])) { require_once ("Rate.php"); $rate = new Rate(); $rate->updateRatingCount($_POST["rating"], $_POST["id"]); } ?>