Page 1 of 1

Complete newbie - How do I calculate the total from mysql?

Posted: Mon May 23, 2005 7:02 am
by mhouldridge
Hi,

I would like to total up the value within my mysql table called dedicated and the row called value.

Can anyone help me.

thanks,
Mark

Posted: Mon May 23, 2005 7:04 am
by shiznatix

Code: Select all

$total = 0;
while ($stuff = mysql_fetch_assoc($query))
{
    $total += $stuff[value];
}

Posted: Mon May 23, 2005 7:33 am
by Chris Corbyn
It can be done within mysql itself.

Code: Select all

$query = "SELECT SUM(value) AS tot FROM `tablename`";

Posted: Mon May 23, 2005 8:09 am
by JayBird
yup, as d11wtq said...it can be done in the query itself and it is best to do it this way

Posted: Mon May 23, 2005 8:52 am
by mhouldridge
Hi,

this is the code that I have;

Code: Select all

<?
$total = SELECT SUM(value) AS tot FROM dedicated";
echo $total
?>
It simply just prints out the SELECT SUM(value) AS tot FROM dedicated"; part

Please help

Posted: Mon May 23, 2005 8:58 am
by JayBird
you need to execute the query first, return the results as an associative array, and the value you want will be in "tot" field

Posted: Mon May 23, 2005 9:05 am
by mhouldridge
urrgh!

I dont know what you mean. Please could you outline the code.

thanks

Posted: Mon May 23, 2005 9:14 am
by JayBird
This is pretty basic stuff

Code: Select all

$sql = "SELECT SUM(value) AS tot FROM dedicated";

$result = mysql_query($sql) or die(mysql_error());

$line = mysql_fetch_array($result, MYSQL_ASSOC);

echo $line['tot'];

Posted: Mon May 23, 2005 9:24 am
by mhouldridge
Thanks for that. I get

Unknown column 'value' in 'field list'

Posted: Mon May 23, 2005 9:44 am
by JayBird
value should be the name of the coulmn you are wanting to add up

Posted: Mon May 23, 2005 9:59 am
by mhouldridge
Yes, that is the name of my column.

Posted: Mon May 23, 2005 10:00 am
by shiznatix
if you can, post your table layout and also post the code you are using now

Posted: Mon May 23, 2005 10:17 am
by mhouldridge
Ah,

Its working now..

thanks for your help.

Posted: Mon May 23, 2005 11:12 am
by John Cartwright
:roll: