I made this simple ajax star rating for my latest poject. And now i want to share it to you. Let’s start it
.
Step 1 : CSS Star Rater
First thing is the star rater. I got this cool ‘css star rater’ from http://www.komodomedia.com/ . I assumed that we already understood how to use it, so we will not talk too much about this ‘css star rater’.
Step 2 : Create MySQL table
Next is create table (using MySQL) to store the data. You can copy the script below
CREATE TABLE IF NOT EXISTS `vote` (
`counter` int(8) NOT NULL default '0',
`value` int(8) NOT NULL default '0'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Step 3 : PHP
After finished create table, then we can start create some php code to handle input, update and retrieve data from the database, here is the code. I added some important comment in it
<?php
// connect to database
$dbh=mysql_connect ("localhost", "username", "password") or die ('Cant connect to the database');
mysql_select_db ("rating",$dbh);
if($_GET['do']=='rate'){
// do rate
rate();
}else if($_GET['do']=='getrate'){
// get rating
getRating();
}
// function to retrieve
function getRating(){
$sql= "select * from vote";
$result=@mysql_query($sql);
$rs=@mysql_fetch_array($result);
// set width of star
$rating = (@round($rs[value] / $rs[counter],1)) * 20;
echo $rating;
}
// function to insert rating
function rate(){
$text = strip_tags($_GET['rating']);
$update = "update vote set counter = counter + 1, value = value + ".$_GET['rating']."";
$result = @mysql_query($update);
if(@mysql_affected_rows() == 0){
$insert = "insert into vote (counter,value) values ('1','".$_GET['rating']."')";
$result = @mysql_query($insert);
}
}
?>
Step 4 : JavaScript
Next thing is javascript code. Below is the code, you can put this code between <head> tag or put it in separated javascript file.
Don’t forget to link the jquery library into your document
Step 5 : Put it all together
Put your css, javascript in one html
Star Rater
That’s it!
. You can add some modification like notification, or loader while processing.
- Download zip file jQuery Tutorial : Simple ajax star rating with php (61)
This article inspired of http://www.yvoschaap.com/
source :: ronggur
payam

