MYSQL PHP getting average of a single field

2020-05-09 01:31发布

问题:

I've made a form that allows users to submit their name, a comment and a score from 1-6, which then is saved in a table in their respective fields; name, comment and score. I wan't to display the average score.

This is what I've found out so far:

$result = mysql_query("SELECT AVG(fieldName) FROM tableName"); 

How do I echo this out?

回答1:

Give your result an alias, It makes accessing it easier.

Use mysql_fetch_assoc() to get your results

$result = mysql_query("SELECT AVG(fieldName) AS avg FROM tableName");
$row = mysql_fetch_assoc($result);
echo $row['avg'];

FYI, mysql_* is obsolete. Try PDO or mysqli instead.