Chrisman Posted April 27, 2008 Share Posted April 27, 2008 I'm very new with PHP and MySQL and I need help with getting the averages from my MySQL database. Basically I'm wanting to make a rating system, and I hope I can just call for an average from the particular table and it will average up all the numbers and display that. I know there is a avg function but I just couldn't get it to work. Any help will be much appreciated. Quote Link to comment Share on other sites More sharing options...
pocobueno1388 Posted April 27, 2008 Share Posted April 27, 2008 Here is an example of how to get an average of a column. <?php $query = mysql_query("SELECT AVG(field_name) as average FROM table"); $row = mysql_fetch_assoc($query); echo $row['average']; ?> Quote Link to comment Share on other sites More sharing options...
Chrisman Posted April 27, 2008 Author Share Posted April 27, 2008 I tried that, and it didn't work. It just puts out a blank. <?php // connecting code... $result = mysql_query("SELECT AVG(rating) AS AVERAGE FROM 5differences") or die(mysql_error()); $row = mysql_fetch_assoc($result); echo "<br />Average ratings of 5differences: ".$row['rating']; // A few other text echo's ?> The page is here to see the exact output. Quote Link to comment Share on other sites More sharing options...
ohdang888 Posted April 27, 2008 Share Posted April 27, 2008 $row['AVG(rating)']; Quote Link to comment Share on other sites More sharing options...
Whitts Posted April 27, 2008 Share Posted April 27, 2008 <?php // connecting code... $result = mysql_query("SELECT AVG(rating) AS AVERAGE FROM 5differences") or die(mysql_error()); $row = mysql_fetch_assoc($result); echo "<br />Average ratings of 5differences: ".$row['rating']; // A few other text echo's ?> should be <?php // connecting code... $result = mysql_query("SELECT AVG(rating) AS AVERAGE FROM 5differences") or die(mysql_error()); $row = mysql_fetch_assoc($result); echo "<br />Average ratings of 5differences: ".$row['average']; // A few other text echo's ?> The name of the value will be whatever is after the "AS". In this case, it is "AVERAGE". If you needed it to be rating, you could easily change it to: SELECT AVG(rating) AS RATING FROM 5differences Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.