Jump to content

[SOLVED] Finding the average from adding multiple entries from db


Recommended Posts

What I want to do is have the code add up all the entries in the database and find the average from a field.

 

Ie, the field name "views" in the table "submissions" and the entries in that field in that table are 234, 365, 264, 646, 354. Add up all of those and get the average number, which in this case is 373 (with the number rounded up to a whole number). I can do the rounding of the number up but I`m not sure how to tell the code to add up all of those numbers from a certain field in the database table.

Ok, I gave it go according to what http://www.tizag.com/mysqlTutorial/mysqlavg.php showed. So I entered this:

 

<?php
$query = "SELECT gallNum, AVG(views) FROM image WHERE gallNum='$g' GROUP BY gallNum"; 
$result = mysql_query($query) or die(mysql_error());

echo "The average views is ".$row['AVG(views)'];

?>

 

I get a blank as a result.

Sorry about that I do not know why I told you to do the sum function when you are trying to get an average I misread the post. Try this:

 

<?php
$query = "SELECT gallNum, AVG(views) AS avg_views FROM image WHERE gallNum='$g' GROUP BY gallNum"; 
$result = mysql_query($query) or die(mysql_error());

echo "The average views is ".$row['avg_views'];

?>

Wow, good call kingphilip. I am seriously going to bed in like 5 mins because I am missing some obvious stuff. Good thing you are following my posts lol. I do like doing it with the AS section though because it is easier to read.

Ok, so I now have:

<?php
$query = "SELECT AVG(views) AS avg_views FROM image WHERE gallNum='$g'"; 
$result = mysql_query($query) or die(mysql_error());
mysql_fetch_assoc($result);

echo "The average views is ".$result['avg_views'];
?>

 

But the result is still blank.

 

Try this:

 

<?php
$query = "SELECT AVG(views) AS avg_views FROM image WHERE gallNum='$g'"; 
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($result))
{
echo "The average views is ".$row['avg_views'];
}
?>

 

You should look more into mysql's data input and retrieval.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.