Jump to content

[SOLVED] How Do I Calculate an Average Review Rating??


webref.eu

Recommended Posts

Hi All

 

I have a Reviews table where people can rate products out of 10.  I need to calculate the average review rating for a particular product.  I think I can do this using the following MySQL query: 

 

$sql4 = "SELECT avg(ReviewRating) FROM Reviews WHERE ReviewIsApproved=1 AND ProductId=" . $ProductId . ";";

 

but how do I actually get the result of this query to display on my page??

 

Many thanks

Thanks for your reply. 

 

I now have this working, and post my code for those interested, the second part of the code calculates the average: 

 

//Find out if there are approved reviews for a product
//Find out how many rows are in the table 
$sql5 = "SELECT COUNT(*) FROM Reviews WHERE ProductId LIKE $ProductId AND ReviewIsApproved=1";
$result5 = mysql_query($sql5, $connection) or trigger_error("SQL", E_USER_ERROR);
$r5 = mysql_fetch_row($result5);
$numrows5 = $r5[0];



//If there are approved reviews, calculate the average review rating
If ($numrows5 > 0) {

//Calculate AverageReviewRating
$sql4 = "SELECT AVG(ReviewRating) FROM Reviews WHERE ProductId LIKE $ProductId AND ReviewIsApproved LIKE 1";
$result4 = mysql_query($sql4);



//obtain
while($row4 = mysql_fetch_array($result4)){
      //mysql_num_rows($result4) always equal to 1 when calculating an average
  //echo mysql_num_rows($result4);
  $AverageReviewRating = $row4['AVG(ReviewRating)'];
  //format to 2 decimal places
  $AverageReviewRating = number_format($AverageReviewRating, 2);
      echo " Average Rating: " . $AverageReviewRating . " / 10";
      }

//End if there are approved reviews 
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.