Alexis Alexis - 13 days ago 5
PHP Question

Adding all rows values in php

This is the table

store_reviews

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
2+5+4/3


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

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


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

Answer

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;
Comments