calculate average from rows in a database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
abhikerl
Forum Newbie
Posts: 9
Joined: Wed Jun 04, 2008 2:07 am
Location: Mauritius

calculate average from rows in a database

Post by abhikerl »

hi, can anyone tell me how to calculate the average of data retrieves from a database. The situation is I have a table "number" which consist of several data like "2,5,4,8,6...." I want to calculate the average and display it on the browser. thanks in advance for your help.

http://www.islandinfo.mu
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: calculate average from rows in a database

Post by onion2k »

madan koshti
Forum Commoner
Posts: 50
Joined: Fri Jun 06, 2008 4:25 am

Re: calculate average from rows in a database

Post by madan koshti »

Hi,

<?php
/* Connecting, selecting database */
$link = mysql_connect("mysql_host", "mysql_user", "mysql_password")
or die("Could not connect : " . mysql_error());
echo "Connected successfully";
mysql_select_db("my_database") or die("Could not select database");

/* Performing SQL query */
$query = "SELECT AVG("filedname") as avg FROM numers";
$result = mysql_query($query) or die("Query failed : " . mysql_error());

$line = mysql_fetch_array($result, MYSQL_ASSOC)) ;
echo "$line['avg']\n";

/* Free resultset */
mysql_free_result($result);

/* Closing connection */
mysql_close();

?>

hope that was needed ???
Post Reply