index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
.star-rating {
width:80px;
height:16px;
float:left;
background:url(ratings.png);
cursor:pointer;
}
.star {
width:16px;
height:16px;
float:left;
}
.result {
float:left;
height:16px;
color:#454545;
margin-left:5px;
line-height:110%;
}
</style>
<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('.star').mouseover(function (){
var star = $(this).index()+1;
var x =(32 * star);
$(this).parent().css('backgroundPosition','0% ' +(-x)+ 'px');
});
$('.star-rating').mouseout(function (){
var originalresult = $(this).attr('id').split('result')[1];
var y =(32 * originalresult);
$(this).css('background-position','0%' +(-y)+ 'px');
});
});
</script>
</head>
<body>
<?php
mysql_connect('localhost','root','');
mysql_select_db('test');
$votes = mysql_query("SELECT rating FROM ratings WHERE id = 1");
$votesnr = 0;
$totalvotes = 0;
while($vote = mysql_fetch_array($votes)){
$votesnr ++;
$totalvotes = $vote['rating'] + $totalvotes;
}
if($votesnr == 0){
echo $rating = 0;
}
else {
echo $rating = $totalvotes/$votesnr;
}
$roundedrating = floor($rating) + round($rating - floor($rating))/2;
?>
<div class="star-rating" id="rating1result<?php echo $roundedrating; ?>" style="background-position:0 -<?php echo $roundedrating * 32; ?>px;">
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
</div>
<div class="result">
<span style="color:green"><?php echo round($rating,2); ?></span> (<?php echo $votesnr; ?>)
</div>
<script type="text/javascript">
$('.star').click(function (){
var id = $(this).parent().attr('id').split('rating')[1];
var vote = $(this).index() + 1;
$.ajax({
type: "POST",
url:"save-vote.php",
data: 'id='+ id + '&vote='+ vote
});
$(this).parent().removeAttr("id");
$(this).parent().html(" ");
});
//replace (and) with the "and" sign - parsing error...
</script>
</body>
</html>
save-vote.php
<?php
mysql_connect('localhost','root','');
mysql_select_db('test');
$votes = mysql_query("SELECT rating FROM ratings WHERE id = 1");
$votesnr = 0;
$totalvotes = 0;
while($vote = mysql_fetch_array($votes)){
$votesnr ++;
$totalvotes = $vote['rating'] + $totalvotes;
}
if($votesnr == 0){
echo $rating = 0;
}
else {
echo $rating = $totalvotes/$votesnr;
}
$roundedrating = floor($rating) + round($rating - floor($rating))/2;
?>
mysql
имя базы данных test
имя таблицы ratings
имя поля id
имя 2 поля rating