user2985194
user2985194

Reputation: 1

MYSQL PHP getting average of a single field

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?

Upvotes: 0

Views: 5347

Answers (1)

John Conde
John Conde

Reputation: 219804

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.

Upvotes: 3

Related Questions