Rating system is very useful to know what a user is liking most.In this tutorial you will learn about creating 5 Star Rating System with PHP,MySQL ,Jquery and Ajax.This tutorial also reduce chances of multiple votes by single user for same product.To prevent multiple votes it will store user’s IP address and also set a cookie in user’s browser .It will check user’s IP address and cookies before inserting any vote into database.
Clik here to view.

Creating 5 Star Rating System with PHP , MySQL ,Jquery and Ajax
If you do not want to read the entire tutorial for Creating 5 Star Rating System with PHP , MySQL ,Jquery and Ajax then follow these steps-
I)-Download the source (link is available at the end of tutorial).
II)-Extract the folder and open settings.php.
III)-Replace values of $host,$uname,$pass and $rating_dbname with your own database host,user name,password and name.
IV)-Upload all files to your server.
V)-Open PHPMyAdmin and import ratings.sql.
Open rating.php by your browser if everything is fine it would work.
Here is the complete guide for creating 5 Star Rating System with PHP , MySQL ,Jquery and Ajax-
1.Create a rating widget using HTML-This is the source of PHP file which will show current ratings and allow a user to rate a particular code .Although this script is incomplete but at the end of the tutorial i will update this file with few PHP code which will retrieve current ratings .Save this file as showrating.php .
<html> <head> <script src="jquery.js" type="text/javascript"></script> <link rel="stylesheet" href="rating.css" /> <script type="text/javascript" src="rating.js"></script> </head> <body> <div class="product"> Rate Item 1 <div id="rating_1" class="ratings"><div class="star_1 ratings_stars ratings_vote"></div><div class="star_2 ratings_stars ratings_vote"></div><div class="star_3 ratings_stars ratings_vote"></div><div class="star_4 ratings_stars ratings_blank"></div><div class="star_5 ratings_stars ratings_blank"></div> <div class="total_votes"><p class="voted"> Rating: <strong>3</strong>/5 (3 vote(s) cast) ; </div> </div><div class="product"> Rate Item 2 <div id="rating_2" class="ratings"><div class="star_1 ratings_stars ratings_vote"></div><div class="star_2 ratings_stars ratings_vote"></div><div class="star_3 ratings_stars ratings_vote"></div><div class="star_4 ratings_stars ratings_vote"></div><div class="star_5 ratings_stars ratings_vote"></div> <div class="total_votes"><p class="voted"> Rating: <strong>5</strong>/5 (5 vote(s) cast) ; </div> </div><div class="product"> Rate Item 3 <div id="rating_3" class="ratings"><div class="star_1 ratings_stars ratings_vote"></div><div class="star_2 ratings_stars ratings_vote"></div><div class="star_3 ratings_stars ratings_vote"></div><div class="star_4 ratings_stars ratings_vote"></div><div class="star_5 ratings_stars ratings_blank"></div> <div class="total_votes"><p class="voted"> Rating: <strong>4</strong>/5 (4 vote(s) cast) ; </div> </div></body></html>
2).Create a style sheet for ratings-This CSS file defines the positions and colors of rating widget you can customize it according to your need.There are three images of star which is used for rating-
I-star_blank.png-It is the default star.
II-star_overs.png-This is mouse over image which will display at the time of mouse over on any star.
III-star_blank.png-This image will show the current rating of product.
Save the given codes as rating.css.
.ratings { border: 1px solid #CCC; overflow: visible; padding: 10px; position: relative; width: 180px; height: 100px; } .ratings_stars { background: url('star_blank.png') no-repeat; float: left; height: 28px; padding: 2px; width: 32px; } .ratings_vote { background: url('star_voted.png') no-repeat; } .ratings_over { background: url('star_overs.png') no-repeat; } .total_votes { background: #eaeaea; top: 58px; left: 0; padding: 5px; position: absolute; } .product{ font: 10px verdana, sans-serif; margin: 0 auto 40px auto; width: 180px; height:200px; }
3). Java Script to handle events –Java Script codes will handle the CSS classes of rating widget and it will sent the ajax request to save rating of users into database.
$(document).ready(function() { $('.ratings_stars').hover( // Handles the mouseover function() { $(this).prevAll().andSelf().addClass('ratings_over'); $(this).nextAll().removeClass('ratings_vote'); }, // Handles the mouseout function() { $(this).prevAll().andSelf().removeClass('ratings_over'); } ); //send ajax request to rate.php $('.ratings_stars').bind('click', function() { var id=$(this).parent().attr("id"); var num=$(this).attr("class"); var poststr="id="+id+"&stars="+num; $.ajax({url:"rate.php",cache:0,data:poststr,success:function(result){ document.getElementById(id).innerHTML=result;} }); }); });
4).Settings for MySQL database- This page stores the host,database name ,user name, password and rating table name in variables.This page also contain a function for connecting MySQL database.To use this script you must need to change $host,$uname,$pass and $rating_dbname.
<?php //settings for 5 Star Rating System with PHP , MySQL ,Jquery and Ajax $rating_tableName = 'ratings'; $rating_unitwidth = 15; $rating_dbname = 'xxx'; $units=5; function connect(){ $host="localhost"; $uname="xxx"; $pass="abc123"; $rating_dbname = 'xxx'; $con = mysql_connect($host,$uname,$pass); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db($rating_dbname, $con);}
5).Create table for ratings-Now you need a table for storing ratings.You can import ratings.sql (which is available in source) from PHPMyAdmin or manually create a table name ratings with columns id,total_votes,total_value and used_ips.
6).PHP Script to save ratings into MySQL database-When a user clicks on any star an AJAX request is send to this page .This page validate the rating of user and saves his rating into database.
<?php //rate.php for 5 Star Rating System with PHP , MySQL ,Jquery and Ajax header("Cache-Control: no-cache"); header("Pragma: nocache"); include("settings.php"); $id_sent = preg_replace("/[^0-9]/","",$_REQUEST['id']); $vote_sent = preg_replace("/[^0-9]/","",$_REQUEST['stars']); $ip =$_SERVER['REMOTE_ADDR'] ; connect(); $q=mysql_num_rows(mysql_query("select id from ratings where id=$id_sent")); if(!$q)mysql_query("insert into ratings (id,date) values ($id_sent,curdate())"); if ($vote_sent > $units) die("Sorry, vote appears to be invalid."); // kill the script because normal users will never see this. //connecting to the database to get some information $query = mysql_query("SELECT total_votes, total_value, used_ips FROM $rating_dbname.$rating_tableName WHERE id='$id_sent' ")or die(" Error: ".mysql_error()); $numbers = mysql_fetch_assoc($query); $checkIP = unserialize($numbers['used_ips']); $count = $numbers['total_votes']; //how many votes total $current_rating = $numbers['total_value']; //total number of rating added together and stored $sum = $vote_sent+$current_rating; // add together the current vote value and the total vote value $tense = ($count==1) ? "vote" : "votes"; //plural form votes/vote // checking to see if the first vote has been tallied // or increment the current number of votes ($sum==0 ? $added=0 : $added=$count+1); // if it is an array i.e. already has entries the push in another value ((is_array($checkIP)) ? array_push($checkIP,$ip) : $checkIP=array($ip)); $insertip=serialize($checkIP); //IP check when voting if(!isset($_COOKIE['rating_'.$id_sent])){ $voted=mysql_num_rows(mysql_query("SELECT used_ips FROM $rating_dbname.$rating_tableName WHERE used_ips LIKE '%".$ip."%' AND id='".$id_sent."' ")); } else $voted=1; if(!$voted) { //if the user hasn't yet voted, then vote normally... if (($vote_sent >= 1 && $vote_sent <= $units)) { // keep votes within range, make sure IP matches $update = "UPDATE $rating_tableName SET total_votes='".$added."', total_value='".$sum."', used_ips='".$insertip."' WHERE id='$id_sent'"; $result = mysql_query($update); if($result) setcookie("rating_".$id_sent,1, time()+ 2592000); } } //end for the "if(!$voted)" // these are new queries to get the new values! $newtotals = mysql_query("SELECT total_votes, total_value, used_ips FROM $rating_tableName WHERE id='$id_sent' ")or die(" Error: ".mysql_error()); $numbers = mysql_fetch_assoc($newtotals); $count = $numbers['total_votes'];//how many votes total $current_rating = $numbers['total_value'];//total number of rating added together and stored $tense = ($count==1) ? "vote" : "votes"; //plural form votes/vote // $new_back is what gets 'drawn' on your page after a successful 'AJAX/Javascript' vote if($voted){$sum=$current_rating; $added=$count;} $new_back = array(); for($i=0;$i<5;$i++){ $j=$i+1; if($i<@number_format($current_rating/$count,1)) $class="ratings_stars ratings_vote"; else $class="ratings_stars"; $new_back[] .= '<div class="star_'.$j.' '.$class.'"></div>'; } $new_back[] .= ' <div class="total_votes"><p class="voted"> Rating: <strong>'.@number_format($sum/$added,1).'</strong>/'.$units.' ('.$count.' '.$tense.' cast) '; if(!$voted)$new_back[] .= '<span class="thanks">Thanks for voting!</span></p>'; else {$new_back[] .= '<span class="invalid">Already voted for this item</span></p></div>';} $allnewback = join("\n", $new_back); // ======================== $output = $allnewback; echo $output; ?>
7).Retrieve Ratings from MySQL Database-This page retrieves the ratings from MySQL Database and display them into form of stars.The output of this page is showratings.php which is used in first step to make this tutorial clear.There is no use of file showratings.php.
<?php include("settings.php"); connect(); $ids=array(1,2,3); ?> <html> <head> <script src="jquery.js" type="text/javascript"></script> <link rel="stylesheet" href="rating.css" /> <script type="text/javascript" src="rating.js"></script> </head> <body> <?php for($i=0;$i<count($ids);$i++) { $rating_tableName = 'ratings'; $id=$ids[$i]; $q="SELECT total_votes, total_value FROM $rating_tableName WHERE id=$id"; $r=mysql_query($q); if(!$r) echo mysql_error(); while($row=mysql_fetch_array($r)) { $v=$row['total_votes']; $tv=$row['total_value']; $rat=$tv/$v; } $j=$i+1; $id=$ids[$i]; echo'<div class="product"> Rate Item '.$j.' <div id="rating_'.$id.'" class="ratings">'; for($k=1;$k<6;$k++){ if($rat+1>$k)$class="star_".$k." ratings_stars ratings_vote"; else $class="star_".$k." ratings_stars ratings_blank"; echo '<div class="'.$class.'"></div>'; } echo' <div class="total_votes"><p class="voted"> Rating: <strong>'.@number_format($rat).'</strong>/5 ('.$v. ' vote(s) cast) </div> </div></div>';} ?> </body></html>
Now your 5 Star Rating System with PHP , MySQL ,Jquery and Ajax is ready you can see the demo and download the complete source from given links.
Common Errors and Solutions-
1-
Notice: Undefined variable: rat in C:\xampp\htdocs\rating\rating.php on line 37
Notice: Undefined variable: v in C:\xampp\htdocs\rating\rating.php on line 41
Solution:Add this line at beginning of rating.php.
error_reporting(E_ALL ^ E_NOTICE);
2-Votes are not saving.
Solution:Try in a different browser with a different IP(or delete manually your votes from table).If problem still persist then print the query of line 40 (ratings.php) and run it from PHPmyAdmin to find out actual problem.
The post Creating 5 Star Rating System with PHP , MySQL ,Jquery and Ajax appeared first on .