Page 1 of 1

PHP MYSQL SUM() ARRAY ...

Posted: Mon Nov 24, 2003 1:50 pm
by nwoutback
I've got this that totals one column ... problem is I have almost 70 columns and I want to add and display each on separately ...

$query = "SELECT SUM(columnname) FROM tablename";
$mysqlresult = mysql_query($query);
$result = mysql_fetch_array($mysqlresult);
echo $result[0];

Any ideas on how I can change this simple SUM to include all my columns?

Thanks.

Posted: Mon Nov 24, 2003 3:30 pm
by Gen-ik

Code: Select all

<?php

$tables = array("tableone","tabletwo","tablethree");

foreach($tables as $tableName)
{
    $query = "SELECT SUM(columnname) FROM `$tableName`";
    $mysqlresult = mysql_query($query);
    $result = mysql_fetch_array($mysqlresult);
    echo "{$tableName} : {$result[0]}<br />";
    musql_free_result();
}

?>

Posted: Mon Nov 24, 2003 3:42 pm
by nwoutback
Thanks ... I changed my code to this but only one column and it's associated SUM value is echoed, can you see what I'm doing that is preventing the other columns and SUM values from displaying?

<?php

$connection=mysql_connect("localhost","user","pw") or die('Could not connect to the database server');
$db = mysql_select_db("tanaka-ism_com", $connection) or die ("Unable to select database.");

$columns = array("AST210","AST210Sales","TBC2251", "TBC2251Sales");

foreach($columns as $columns)
{
$query = "SELECT SUM($columns) FROM distreport03";
$mysqlresult = mysql_query($query);
$result = mysql_fetch_array($mysqlresult);
echo "{$columns} : {$result[0]}<br />";
musql_free_result();
}

?>

Posted: Mon Nov 24, 2003 3:47 pm
by nwoutback
Nevermind ... found typo.