webref.eu Posted June 6, 2009 Share Posted June 6, 2009 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 Quote Link to comment https://forums.phpfreaks.com/topic/161187-solved-how-do-i-calculate-an-average-review-rating/ Share on other sites More sharing options...
Axeia Posted June 6, 2009 Share Posted June 6, 2009 Just like you do with anything else. If you're confused about the avg not having a columnname then use SELECT AVG(ReviewRating) AS avgRating and the columname you can use then is avgRating. Quote Link to comment https://forums.phpfreaks.com/topic/161187-solved-how-do-i-calculate-an-average-review-rating/#findComment-850582 Share on other sites More sharing options...
webref.eu Posted June 6, 2009 Author Share Posted June 6, 2009 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 } Quote Link to comment https://forums.phpfreaks.com/topic/161187-solved-how-do-i-calculate-an-average-review-rating/#findComment-850597 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.