Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Working Out Total 1

Status
Not open for further replies.

sipps

Technical User
Feb 9, 2003
133
GB
Hi all,

I have a page which shows a customers order, what products they have bought, the quantity, and the price of the item.

I can loop through the db to get all the items the customer bought, and I can get the value of these items and * it by the quantity to get the total value for both those items.

However, I am having problems getting the total amount for that order.

Here is the code that gets all the items from an order:
<?php do { ?>

<tr>
<td><?php echo $row_getitems['Item_Name']; ?></td>
<td><?php echo $row_getitems['Quantity']; ?><td>
<td><?php echo $row_getitems['Sell_Price']; ?></td>
<td><?php echo $ordercost=$row_getitems['Quantity'] * $row_getitems['Sell_Price'];?>
<td>
</tr>
<?php } while ($row_getitems = mysql_fetch_assoc $getitems)); ?>

Which could output something like this:

ItemName Quantity ItemPrice Cost
Tie 2 3.50 7.00
Socks 4 3.00 12.00

I now want to loop through the $ordercost to get the total for the whole order, but I can't seem to get it right, so far I have written:

<?php
// loop number of items
$total = 0;
for($k=0; $k < count($row_getitems = mysql_fetch_assoc($getitems)); $k++) {
$total += $ordercost[$k]; } echo &quot;Total = &quot; . $total; ?>

I am not sure what to do, please can anyone suggest something?

Thank you

sipps
 
Replace

<td><?php echo $ordercost=$row_getitems['Quantity'] * $row_getitems['Sell_Price'];?>

with

<?php
$temptotal = $row_getitems['Quantity'] * $row_getitems['Sell_Price'];
$total = $total + $temptotal;
?>

<td><?php echo $temptotal;?>

that will give you $total as the total cost of everything. and there should be a closing </td> tag at the end of that line btw.
 
Thats great KempCGDR, it works fine!

Should I define $total=0; at the top of that page, because I am getting an undefined variable error?

Thank you again,

sipps
 
Sipps,

Just a note to your post above:
It's a good idea to initialize every variable (PERL programmers are especially strict with this).
When you operate PHP with TRACK_GLOBALS_ON anyone could set the uninitialized variable through a get parameter. ALl they needed to do is add yourscript.php?total=-34 and mess up your calculation.
 
Thank you DRJ478,

I shall initialize it at the top. Once it's initialised, does this mean that it is ok to have TRACK_GLOBALS_ON?

Thanks

sipps
 
Sipps,

Yes. Because, no matter what is set to $total through _GET[total], the statement $total = 0 will override it.
You should be fine!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top