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. Link to comment https://forums.phpfreaks.com/topic/103096-solved-averages-from-mysql/ 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']; ?> Link to comment https://forums.phpfreaks.com/topic/103096-solved-averages-from-mysql/#findComment-528116 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. Link to comment https://forums.phpfreaks.com/topic/103096-solved-averages-from-mysql/#findComment-528144 Share on other sites More sharing options...
ohdang888 Posted April 27, 2008 Share Posted April 27, 2008 $row['AVG(rating)']; Link to comment https://forums.phpfreaks.com/topic/103096-solved-averages-from-mysql/#findComment-528145 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 Link to comment https://forums.phpfreaks.com/topic/103096-solved-averages-from-mysql/#findComment-528146 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.