0

How can I calculate the average of column values in a mySQL table and display it in an HTML table?

$conn = mysql_connect($dbhost, $dbuser, $dbpass);

$sql = 'SELECT AVG(price) FROM emp';
$retval = mysql_query( $sql, $conn );
$values = mysql_num_rows($retval);

echo $values;

It returns 1. I feel like the problem is with mysql_num_rows() but what will be the correct code to display the average output?

Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
Niks
  • 41
  • 2
  • 11
  • `$values = mysql_fetch_array($retval);` ? – Peon Jan 03 '14 at 14:40
  • `mysql_num_rows()` is used to return the number of rows from a result set. If you want the actual *value*, you need to use a `mysql_fetch_*` function, such as `mysql_fetch_array()`, or `mysql_fetch_assoc()`. Also, I suggest you [enable error reporting](http://stackoverflow.com/a/6575502/1438393) to see the error messages. – Amal Murali Jan 03 '14 at 14:49

1 Answers1

1
$sql = 'SELECT AVG(price) FROM emp';
$retval = mysql_query( $sql, $conn );

$values = mysql_num_rows($retval);
echo $values;//it will display the number of rows of your resultant table

$avg=mysql_result($retval,0);

echo $avg;//it will show the average

Dont use mysql_* as they are depracated.time to move on to mysqli_* or PDO.

R R
  • 2,999
  • 2
  • 24
  • 42