Alexis Alexis - 2 months ago 16
PHP Question

Adding all rows values in php

This is the table


id rev_star
1 2
2 5
3 4

What I want to do is to get all the rows and add stars and divide by the count of rows (average) like

I wrote a code but it doesn't get all the rows added.

$stmtrev = $mysqli->prepare("SELECT * FROM store_reviews WHERE store_id=?");
$stmtrev->bind_param("i", $_GET['storeid']);
$revrows = $stmtrev->get_result();
while ($stars = $revrows->fetch_assoc())
$count = ($total + $stars['rev_star']);

Can anyone explain what's wrong and what could be done?


This is one of those places where your database can do the work for you

SELECT AVG(rev_star) as average, 
FROM store_reviews 
WHERE store_id=?

As to why your PHP script isn't working properly, you're counting the number of columns in your database, not the number of rows. Worse, you're doing this by trying to pop a result set off the result stack after having looped through the full result stack. The result object tells you how many rows were returned

$total = 0;
while ($stars = $revrows->fetch_assoc()) $total += $stars['rev_star'];
$avg = $total / $revrows->num_rows;