PHP jQuery Star Rating
I was looking to create PHP jQuery star rating and luckily came across this script. I have created a very easy steps below so that even a layman can make this work with basic PHP and jQuery knowledge.
1. Create table using following SQL Query
CREATE TABLE IF NOT EXISTS `ratings`
( `rating_id` int(11) NOT NULL AUTO_INCREMENT,
`rating_article_id` int(11) NOT NULL,
`rating_num` int(11) NOT NULL,
`rating_ip` varchar(25) NOT NULL,
`rating_date` date NOT NULL,
PRIMARY KEY (`rating_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
2. Create following PHP functions
function selectRating($article_id){
$ip = $_SERVER['REMOTE_ADDR'];
$dublicate_val = $this->checkDublicateRating($article_id,$ip);
$total_rating_star = 5;
$rating_star =NULL;
$sql = "SELECT SUM(rating_num)AS total_rate,
COUNT(*) AS total_row
FROM ratings WHERE
rating_article_id = '$article_id'";
$resRating = mysql_query($sql);
$recRating = mysql_fetch_array($resRating);
if($recRating['total_row']>0) {
$average = floor($recRating['total_rate']/$recRating['total_row']);
$rate_percentage =($recRating['total_rate']
/($recRating['total_row']*$total_rating_star))*100;
}
else
{
$average =0;
$rate_percentage=0;
}
//echo $average;
for($i=1;$i<=$average;$i++) {
if($dublicate_val==0) {
$ratval = $i;
$rating_star.="
";
}
else
{
$rating_star.="";
}
}
for($i=$average+1;$i<=$total_rating_star;$i++) {
if($dublicate_val==0) {
$ratval = $i;
$rating_star.="
";
}
else
{
$rating_star.="";
}
}
$rating_star="
".$rating_star."";
$rating_star .="Percentage:-
".number_format($rate_percentage, 2, '.', '')."%";
$rating_star .= "
Total Rate:- ".$recRating['total_row']."
";
return $rating_star;
}
function checkDublicateRating($id,$ip) {
$sql="SELECT COUNT(*) AS total_row FROM ratings
WHERE rating_article_id = '".$id."'
AND
rating_ip='".$ip."'";
$resCheck = mysql_query ($sql);
$recCheck = mysql_fetch_array($resCheck);
return $recCheck['total_row'];
}
function insertRating($rate_id,$article_id)
{
$ip = $_SERVER['REMOTE_ADDR'];
if($this->checkDublicateRating($article_id,$ip)==0)
{
$sql="INSERT INTO ratings
SET rating_article_id = '".$article_id."',
rating_num='".$rate_id."', rating_ip='".$ip."',
rating_date=CURDATE()";
mysql_query ($sql);
}
}
/// EOF
3. Create select_rating.php file with following piece of code
4. Create insert_rating.php file with following piece of code
5. Create main file where you want to load the rating lets say index.php you can use following fiece of code in this page
Rating