Jump to content

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


djfox

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.

Link to comment
Share on other sites

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'];

?>

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.