How to use avg function?

柔情痞子 提交于 2021-02-07 18:42:38

问题


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.


回答1:


Solution for Q1: SELECT AVG(column1) FROM table1

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




回答2:


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



回答3:


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)'];
}


来源:https://stackoverflow.com/questions/3010715/how-to-use-avg-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!