Hi,
Im making a 5 star rating system but half the time it has the complete wrong result. I have gone over and over the script and checked the sums with a calculator and it is still doing something wierd. Sometimes when I rate it above it's current rating it moves the overall rating down...
The page that links to the php file just has links to the php file with the appropriate PID (product ID) and user's rating, for example index.php?pid=1234&rating=5. The ratings are between 1-5.
anyway, the code I currently have is below:
(by the way, apologies for the crappy notes, im not a mathmatician so find it difficult to explain what i'm doing.)
//get product id and user's rating
$pid = $_GET['pid'];
$newrating = $_GET['rating'];
//connect to db
include('../../php/database/connect.php');
//get current values from that product in the db
$query = "SELECT * FROM products WHERE pid = '".$pid."'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
//get current number of rates
$numberofrates = $row['numberofrates'];
$numberofrates = (int)$numberofrates;
//get current rating
$rating = $row['rating'];
$rating = (int)$rating;
//multiply current rating by number of ratings then increment number of rates by 1 to include new rating, and add user's rating to total rates to recreate average
$rating = $rating * $numberofrates;
$newnewrating = $rating + $newrating;
$numberofrates = $numberofrates + 1;
$newnewrating = $newnewrating / $numberofrates;
mysql_query('UPDATE `web163-zavvex`.`products` SET `rating` = "'.$newnewrating.'" WHERE `products`.`pid` = "'.$pid.'" LIMIT 1');
mysql_query('UPDATE `web163-zavvex`.`products` SET `numberofrates` = "'.$numberofrates.'" WHERE `products`.`pid` = "'.$pid.'" LIMIT 1');
echo $newnewrating;
}
Thanks in advance for pointing out where I have gone wrong :)
Max