Jump to content

Totalling in a For loop


FlashNinja

Recommended Posts

So I'm coding together a basket/cart for an e-commerce site. I have the contents of the basket being echoed out in a FOR loop, including the price of each item. I'm not sure though how to exactly add together all of the basket item prices together while they are in a FOR loop in order to produce a total sum for the basket contents. Could anyone give me some pointers?

 

Here's the FOR loop:

 

$uid = $_SESSION['id'];
$sql = "SELECT * FROM basket WHERE session = '$uid'";
$basket = mysql_query($sql) or die (mysql_error());
$numrows = mysql_num_rows($basket);

for($count = 1; $count <= $numrows; $count++)
   {
   $baskets = mysql_fetch_array($basket);
   $bid = $baskets['contents'];
   $sql2 = "SELECT * FROM games WHERE id = '$bid'";
   $item = mysql_query($sql2) or die (mysql_error());
   $items = mysql_fetch_array($item);
   $name = $items['name'];
   $gid = $items['id'];
   
   echo "<div id = 'strip'>";
   echo "<a href=game_page.php?game=" . $gid . ">" . $name . "</a>";
   echo "</div>";
   echo "<div id = 'basprice'>";
   echo "Price: ?".$items['price'];
   echo "</div>";
   echo "<br>";
   echo "<br>";
   echo "<br>";
   }

Link to comment
https://forums.phpfreaks.com/topic/265966-totalling-in-a-for-loop/
Share on other sites

Run a query like this

 

SELECT
  games.name,
  games.price
FROM
  basket
  LEFT JOIN games ON basket.itemID = games.gameID
WHERE
  basket.session = '$uid'

 

That should get all the information you need in a single query (save you from having to loop queries).

 

You can then get a running total while you're looping through the items.

 

<?php

$result = mysql_query($the_query_posted_above);

// start running total at 0
$total = 0;
if( $result != FALSE ) {
while($row = mysql_fetch_assoc($result)) {
	echo "{$row['name']}: \${$row['price']}<br>";
	// add current price to running total
	$total += $row['price'];
}
// output total cost after displaying items
echo "Total cost: \$$total";
} else {
echo 'Query failed';
}

?>

IMO that LEFT JOIN should be just JOIN. Since you are selecting only games.* related info you'll end up with a result row that has NULL** as value for both columns when a game does indeed end up in the basket yet managed to disappear afterwards.

 

To the customer it will end up as an empty order line in the checkout.

 

** Assuming the OP did not use INNODB with a referential ON DELETE constraint.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.