ColdFusion Programming/Addtion equations inside a loop

Advertisement


Question
Hello,
I have a table in my database show below:

Name:     Cost:
Trees     3000
Leaves    12500
Branches  2000

basically I want to display the above on a page, which I can do, but what I then need to do is display the total cost at the end.
So if the query is:

<cfquery name="qDisp" datasource="content">
SELECT name, cost
FROM tablename
</cfquery>

and the output is something like:

<p>
<cfoutput query="qDisp">
#name#:  £#cost#<br>
</cfoutput>
</p>

How do I get something like this at the bottom:

<hr>
Total cost: ??

Answer
The easiest way is to include the total in your query.

SELECT name, cost, sum(cost) as TotalCost

The other way is a bit more cumbersome but can be done.

<cfset tCost = 0>
<cfoutput query="qDisp">
#name# : #cost#<br>
<cfset tCost = tCost + #cost#>
</cfoutput>
<hr>
<cfoutput>#tCost#</cfoutput>

ColdFusion Programming

All Answers


Answers by Expert:


Ask Experts

Volunteer


Donald Hammond

Expertise

Expert in ColdFusion, Flash ActionScript, XML, and SQL.

Experience

Cold Fusion, Flash Action Script

©2012 About.com, a part of The New York Times Company. All rights reserved.