MYSQL PHP getting average of a single field

笑着哭i 提交于 2019-12-02 16:40:19

问题


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.



来源:https://stackoverflow.com/questions/19941050/mysql-php-getting-average-of-a-single-field

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