问题
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?
- MySQL SELECT syntax
- MySQL AVG() function - there is even an example of exactly what you need
- PHP mysql_fetch_assoc() function which is one of several ways to retrieve data from result set
- 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