Jump to content


This topic is now archived and is closed to further replies.


[SOLVED] Sum of a mysql column

Recommended Posts

I have a table with a column that pulls a decimal value from a mySQL table. Is there a way that I can sum up that entire column?


<table id='menuDisplayTable'>
            <col id='restCol' />
            <col id='cityCol' />
            <col id='priceCol'  />
            <col id='timeCol' />
            <col id='delete' />
        <th scope='col'>Restaurant</th>
        <th scope='col'>City</th>
        <th scope='col'>Price</th>
        <th scope='col'>Date</th>
        <th scope='col'>Delete</th>

//we need to color every odd row so that its easier to read. Create a row variable
$rows = 1;
print "<tr>";

while($row = mysql_fetch_array($result))
	$ID = $row['recID'];
	$rest = $row['restID'];
	$city = $row['cityID'];
	$price = $row['price'];
	$timedate = $row['time'];

print "<td>$restName</td><td>$cityName</td><td>$$price</td><td>$timedate</td><td><a href='processDeleteReceipt.php?deleteID=$ID'>Delete</a></td>";
//If the row ends, and its odd, set the tr class to odd
	print "<tr class='odd'>";
	$rows = 0;

	print "</tr>";
	} //$row else end


print "<tr><td>Sum: </tr>";
print"</tbody> </table>";



Share this post

Link to post
Share on other sites

SELECT SUM(column_name) FROM table;



Or if you wanted to do it in PHP, psuedo code:




$total = 0;
while($r = mysql_fetch_assoc($q)) {
    $total += $r['column_that_holds_value_you_want_to_add'];


I suggest doing it in MySQL though, especially if you don't plan to pull all of the values to begin with.  If you do it in MySQL, it will most likely do a full table scan, so if it's a large table, you might run into issues with it, but in the same sense, if it's a large set of data, PHP would take a while too.

Share this post

Link to post
Share on other sites

ok, what do i set the variable to?



$query="SELECT SUM(price) FROM clientReceipt WHERE userID = $userID";

print "<tr>";
while($row = mysql_fetch_array($result))
	//Here is where im confused
               $sum = $row['price'];
	print "<td>Sum: $sum </td>";

print"</tr></tbody> </table>";

Share this post

Link to post
Share on other sites

You either need to use a numeric index (mysql_fetch_row or mysql_Fetch_array with numeric indexes enabled), or you'll need to use an alias:



SELECT SUM(price) AS price_total FROM clientReceipt WHERE userID = $userID



Then you would use price_total as the name.

Share this post

Link to post
Share on other sites

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.