Jump to content

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 
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.