phprating-system

calculate total avarage Rating php


how to calculate the total average (user) rating

EXAMPLE: user ratings 20 average 4.3

$result=mysqli_query($connection,"SELECT * FROM rating where to_user_id='".userid."'"); 

count

$rowcount=mysqli_num_rows($result);
  echo  $rowcount; // Result 20 ratings

Ratings

   while($row = mysqli_fetch_array($result)){
                    echo  $row['ratting'];// 1.0 2.0 4.0.......

                    ?>

My problem how can I calculate the total average

  example like a total average of 4.3

please help me


Solution

  • You can achieve this all in MySQL:

    SELECT to_user_id, COUNT(rating) AS total_ratings, AVG(rating) AS average_rating FROM rating WHERE to_user_id = 123 GROUP BY to_user_id

    echo "{$row['to_user_id']} has an average rating of {$row['average_rating']} from a total of {$row['total_ratings']} rating(s)";