Adding together the results of a query

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • randomdave
    New Member
    • Jan 2007
    • 1

    #1

    Adding together the results of a query

    Hi. I've been banging my head against this for hours and would greatly appreciate any help that can be offered. Basically I want to add together the results of a query, so I can then call the total as $total to use later in the page. Here's an example (not the real thing but a simplified version of the concept):

    Say I had a table containing two fields, one for a person's name, and one for their age. How would I call all the entries and add together the people ages (so if I had three entries with the ages 20, 45 and 12, how would i add those up to give myself a total of 77?)?

    Many thanks to anyone who can help with this. It seems every way I turn it wont quite work for some reason or other.

    Dave.
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    Because you post this question in the PHP forum, you must require a PHP answer.
    [php]
    $total=0;
    $sql = "SELECT * FROM table";
    $query = mysql_query($sq l)
    or die ("Query error: " . mysql_error());
    while ($row=mysql_fet ch_assoc($query )) {
    echo "{$row['name']} - {$row['age']}<br />";
    $total += $row['age'];
    }
    echo "Total = $total";
    [/php]
    ronald :cool:

    Comment

    Working...