View Full Version : ARRAY_SUM advice

12-02-2009, 08:10 PM
Need a bit of help guys.

I am building a rating system. To do this I am counting the rows from my table and getting the rating from each row using this......

$result = mysql_query("SELECT COUNT(*) FROM ratings WHERE imageID = '$imageID'");
$row = mysql_fetch_row($result);
$numrows = $row[0];

$query = "SELECT * FROM ratings WHERE imageID = '$imageID'";
$result = mysql_query($query);
$rating = mysql_fetch_array($result);

while($rating = mysql_fetch_array($result)){
$rating = $rating['rating'];

I need to add up the result of the while loop so I can then find the average rating by dividing the total by the number of rows. I think I need to use ARRAY_SUM but cant figure it out.

How do I total the result of the while loop?

Thanks all, Paul

12-03-2009, 12:20 AM
yes hvenat thought this through but the operator to think about is +=

so $result += $result will add the previous valueso you couls maybe echo that into your loop and arrive with the total at the end of the loop

12-12-2009, 12:04 AM
Sorry Edbr, I sorted this but forgot to post back.

Here is what I ended up doing in case it helps anyone else.


$query = "SELECT * FROM ratings WHERE imageID = '$imageID' ORDER BY ratingID DESC";
$result = mysql_query($query);

while($rating = mysql_fetch_array($result)){
$ratings[] = $rating['rating'];
$sum_total = @array_sum($ratings);

$new_rating = $sum_total/$numrows;

$rating = ceil($new_rating);