-3

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

Community
  • 1
  • 1
CforCODE
  • 105
  • 6

5 Answers5

1

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)";

Mike G
  • 64
  • 5
0

consider using mysql AVG function and group by user

SELECT AVG(rating) _avg from ratings group by user;

https://www.w3schools.com/sql/func_mysql_avg.asp

cfv1000
  • 453
  • 3
  • 10
0

You can try this :

$average = array_sum($row['ratting']) / count($row['ratting']);

print_r($average);
Adrian Edy Pratama
  • 3,841
  • 2
  • 9
  • 24
  • getting results like this 306 305.71428571429 305.71428571429 305.85714285714 305.14285714286 305.42857142857 306.28571428571 306.28571428571 306.57142857143 306.85714285714 300.28571428571 300.42857142857 307.28571428571 307.42857142857 332.85714285714 333.14285714286 –  CforCODE Nov 29 '19 at 06:39
  • Ah sorry, you must get the data from the `ratting`, not the row – Adrian Edy Pratama Nov 29 '19 at 06:43
0

SELECT (sum(ratting)/count(ratting)) as average FROM rating ;

add the scores and count them, the rest takes care of SQL.

-1

Hi you can be use this:-

$result=mysqli_query($connection,"SELECT AVG(rating) as average_rating FROM rating where to_user_id='".userid."'"); 
Balasaheb Bhise
  • 235
  • 1
  • 7