Forum Moderators: coopster

Message Too Old, No Replies

PHP calculates average?

         

lickuid

11:21 am on Aug 28, 2003 (gmt 0)



Does anybody have a [short smart] script for calculating average from MySQL database columns? Thx for great help!

//lickuid//

justageek

11:26 am on Aug 28, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Use the mysql avg.

select avg(Price) from wherever where whatever

or select avg(Price) as a from wherever where whatever

the second will return a variable called 'a' with the value in it so you can go do something with it if you wish.

Mysql is much faster than doing any kind of calculations in the result set with php.

jonknee

3:48 am on Sep 1, 2003 (gmt 0)

10+ Year Member



If for some reason you needed to do it in PHP, it's not hard (but as it has already been pointed out that it is much slower):

<?php
//must already be connected to MySQL
$r = mysql_query("SELECT * FROM table");
$num = mysql_num_rows($r);
while($data = mysql_fetch_array($r)) {
$total = $data['column'] + $total;
}
$avg = $total / $num;
echo $avg;
?>