dygta
dygta

Reputation: 81

Coldfusion Calculate Sum Total (Loop? )

ok. so i have this table:

|item| quantity| price|

|apple | 2 | 2.00 |
|orange | 3 | 1.50 |
|grape | 5 | 2.50 |

i want to display the Grand Total that a customer has to pay. how to do that? enter code here i don't really know how to use array. can anyone show me how?

my code (sort of)

the price is shown in each of the row using this query:

<cfquery name="getPrice" datasource="fruits">
select *
from fruits
</cfquery>

<cfloop query="getPrice">
  #quantity# | #price# | #totalPrice#
</cfloop><br>

the Grand Total should be displayed in the last row (Grand Total =$ 21.00 ).

Thanks for your help.

Upvotes: 1

Views: 4173

Answers (2)

Justin Scott
Justin Scott

Reputation: 865

If ALL you want is the grand total, you can do that in SQL without looping over the records as:

<cfquery name="getPrice" datasource="fruits">
  select sum(price*quantity) as grandTotal
  from fruits
</cfquery>

Total: <cfoutput>#getPrice.grandTotal#</cfoutput>

Upvotes: 4

charliegriefer
charliegriefer

Reputation: 3382

<cfset grandTotal = 0 />

<cfloop query="getPrice">
    #quantity# | #price# | #totalPrice#<br />
    <cfset grandTotal = grandTotal + ( price * quantity ) />
</cfloop>

<br /><br />

<cfoutput>#grandTotal#</cfoutput>

Upvotes: 7

Related Questions