ColdFusion Programming/Addtion equations inside a loop
Expert: Donald Hammond - 6/23/2008
QuestionHello,
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: ??
AnswerThe 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>