tags:

views:

64

answers:

3

I'm new at php and mysql stuff and i'm trying to use an avg function but i don't know how to.

I'm trying to do something like this:

mysql_connect(localhost,$username,$password);

@mysql_select_db($database) or die ("Did not connect to $database");

mysql_query("AVG(column1) FROM table1 ") or die(mysql_error());

mysql_close();

echo AVG(column1);

(Q1)I'd like to see the value printed in the screen, but i'm getting nothing but an error message. How could I print this average on the screen ?

(Q2)If I had a column month in my table1, how could I print the averages by the months ?

Sorry for any bad English, and thanks for the attention.

+2  A: 

Solution for Q1: SELECT AVG(column1) FROM table1

Solution for Q2: SELECT AVG(column1), month FROM table1 GROUP BY month

Svisstack
A: 

What to read?

  1. MySQL SELECT syntax
  2. MySQL AVG() function - there is even an example of exactly what you need
  3. PHP mysql_fetch_assoc() function which is one of several ways to retrieve data from result set
  4. btw: PDO is much better for database communication in PHP

Ad. 1:

$sql    = 'SELECT AVG(col_name_1) AS avgColName FROM tbl_name;';
$query  = mysql_query($sql);
$result = mysql_fetch_assoc($query);

var_dump($result['avgColName']);

Ad. 2:

SELECT ... FROM ... GROUP BY MONTH(date_col_name);
Crozin
I'm getting it like this 'string(6) "3.5000"', 3.5 is the correct avg, can i print it without the string(6) and wihtout the "" ?Thank you very much.
Marcelo
Of course... just take a look on what [`var_dump()`](http://pl.php.net/manual/en/function.var-dump.php) does. Use [`echo`](http://pl.php.net/manual/en/function.echo.php) instead.
Crozin
A: 

You need to return the result of the query into a variable which you can then use.

For example:

$query = "AVG(column1) FROM table1";     
$result = mysql_query($query);

// Print out result
while($row = mysql_fetch_array($result)) {
echo $row['AVG(column1)'];
}
Michael Baker