Reputation: 582
All i am doing is saving user ratings and reviews to table and then calling it from database. Now what I want to do is add all the ratings (like: 5+4+3= 12) and then divide them by count of the ratings (12/3 = 4) and get average rating or aggregate rating.
I am able to display the reviews but how can I add all values from rating column and get average value.
if (mysqli_num_rows($mesult) > 0) {
$count = mysqli_num_rows($mesult);
echo '<p class="">'.$count.' Reviews</p>';
while($row = mysqli_fetch_assoc($mesult)) {
$name =$row["name"];
$text =$row["text"];
$heading =$row["heading"];
$rating =$row["rating"];
echo '<div class="review" itemscope itemtype="http://schema.org/Review"> <meta itemprop="itemReviewed" content ="'.$title.'"/> <p class="heading"><strong>'.$heading.'</strong></p><div class="ratings" itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating"> <meta itemprop="worstRating" content = "1"/><span itemprop="ratingValue">'.$rating.'</span>/<span itemprop="bestRating">5</span></div><p class="reviewtext" itemprop="description">'.$text.'</p><div class="reviewby" itemprop="author" itemscope itemtype="http://schema.org/Person"><span itemprop="name">'.$name.'</span></div></div>';
}
Also what I am querying is
$loutput ="SELECT * FROM rating
WHERE product=$ID";
$mesult = mysqli_query($conns,$loutput);
Upvotes: 0
Views: 276
Reputation: 520
$loutput ="SELECT AVG(Column_name) as avg FROM rating WHERE product='".$ID."'";
$mresult=mysqli_fetch_assoc(mysqli_query($loutput));
echo $mresult['avg'];
Upvotes: 2
Reputation: 125
Use aggregate function to get the average use the avg()
SELECT avg(rating) from rating;
Upvotes: 0
Reputation: 3962
You can also use MySQL's AVG() to calculate the average rating:
SELECT AVG(rating) AS avgRating FROM myTable;
This is how you round the result to X decimals:
SELECT ROUND(AVG(rating), X) AS avgRating FROM myTable;
Upvotes: 5