5

I am developing a star rating system with 1-5 stars. In my database I am saving them like this:

$stars_1 = 1;
$stars_2 = 6;
$stars_3 = 3;
$stars_4 = 11;
$stars_5 = 22;

$total_votes = 43

When a user votes using for example 3 stars I update stars_3 with 1 and total_votes with 1. Then I need to calculate the average rating (stars).

I do it like this right now but I is not working (result seems wrong):

(($stars_1 + $stars_2 + $stars_3 + $stars_4 + $stars_4) / $total_votes);
Jonathan Clark
  • 19,726
  • 29
  • 111
  • 175
  • 1
    What is the difference between $stars_1 and $stars_5, if at the end you average them? $stars_1 and $stars_5 play the same role. – Anton Sementsov Mar 19 '12 at 10:20

2 Answers2

13

Needs to be like this:

($stars_1 + $stars_2 * 2 + $stars_3 * 3 + $stars_4 * 4 + $stars_5 * 5) / $total_votes;
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
2

You need to multiply the number of stars with the actual rating. Like

$points_stars_2 = $stars_2 * 2  
...  
$points_stars_5 = $stars_5 * 5 

And then you add them all to one variable like in your code, and then divide it by $total_votes.

Regards

Carl0s1z
  • 4,683
  • 7
  • 32
  • 47
Tobias
  • 873
  • 9
  • 17