adding up columns<

liunx

Guest
Is there a way I could use PHP to add up all of the rows under a certain column in my MySQL table? So for example:
Let's say this is my table:
-----------
|COL1|COL2|
-----------
|FiRST|23|
----------
|SeCoNd|4|
----------
|next|6|
---------

So what i want it to do is to get all the values for COL2 and add them together to get a total which will be echoed. The one thing that makes this more complicated is that new rows will be added and the values of COL2 will change, but I could use anything to get me started.Well...


$colSum = 0;
$sql = "select * from -your-table-";
$query = mysql_query($sql);
while ($row=mysql_fetch_array($query)) {
$colSum += $row["COL2"];
}

echo $colSum;


That should add up everything in the Col2You could also do

$sum = mysql_query("SELECT SUM(COL2) FROM table");
 
Back
Top