How to use avg function?
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_connec开发者_如何学编程t(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.
Solution for Q1: SELECT AVG(column1) FROM table1
Solution for Q2: SELECT AVG(column1), month FROM table1 GROUP BY month
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);
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)'];
}
精彩评论