Hi,

I'm doing a very simple shopping cart for my website and I'm quite rusty at PHP and have forgotten how to calculate the grand total in my shopping cart. I am able to calculate the subtotal in every row but now I need to get the total of all the rows put together.

Basically I have a mysql database which records all the products added to a cart during a session. In my basket.php file, I retrieve all the products for this particular session using a database query as follows:

<?php
$result = mysql_query( "SELECT FROM Shopping_sessions WHERE Session_id='$ses_id'", $db);
if (!$result) {
echo("<p>Error performing query1: " . mysql_error() . "</p>");
exit();
}
?>
<table width="100%" cellpadding="3" cellspacing="0" bgcolor="#FAF9CF">
<tr>
<td height="30"><strong>Item</strong></td>
<td width="120"><strong>Quantity</strong></td>
<td width="80"><strong>Item Price</strong></td>
<td width="80"><strong>Subtotal</strong></td>
</tr>
<?php
while($row = mysql_fetch_array($result)){
$Product_quantity = $row["Quantity"];
$Product_id = $row["Product_id"];
$result2 = mysql_query( "SELECT
FROM Products WHERE Product_id=$Product_id", $db);
if (!$result2) {
echo("<p>Error performing query1: " . mysql_error() . "</p>");
exit();
} // query
$row2 = mysql_fetch_array($result2);
$Product_name = $row2["Product_name"];
$Product_price = $row2["Product_price"];
$total1 = $Product_quantity * $Product_price;
$total2 = number_format($total1, 2);
echo "<tr> <td>$Product_name</td>
<td>$Product_quantity</td>
<td>$Product_price</td>
<td>$total2</td>
</tr>";
}
?>

// SO FAR SO GOOD, HERE IS WHERE I NEED HELP

How do I calculate the combined value of $total2?

    $grand_total +=$total1;

    inside the loop, after each total1 is calculated. It simply adds $total1 to $grand_total each time, at the end of the loop, you have your result.

      Please use the formatting tags described in the FAQ when posting; thank you.

        Thanks, that worked. I knew it was something very simple but couldn't remember how to do it.

          Write a Reply...