PHP MYSQL SUM() ARRAY ...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nwoutback
Forum Newbie
Posts: 17
Joined: Mon Nov 24, 2003 1:50 pm

PHP MYSQL SUM() ARRAY ...

Post 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.
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post 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();
}

?>
nwoutback
Forum Newbie
Posts: 17
Joined: Mon Nov 24, 2003 1:50 pm

Post 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();
}

?>
nwoutback
Forum Newbie
Posts: 17
Joined: Mon Nov 24, 2003 1:50 pm

Post by nwoutback »

Nevermind ... found typo.
Post Reply