Jump to content

Recommended Posts

Okay,

I think this might be quite basic but I am still trying to learn and not entirely sure how to do this!

 

I want to create a sum of all $qty values from the script below and then display this sum at the bottom. What is the best way of doing this?

 

function printCart() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
	$items = explode(',',$cart);
	$contents = array();
	foreach ($items as $item) {
		$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
	}
	$output[] = '<form action="basket.php?action=update" method="post" id="cart">';
	$output[] = '<table width="600" align="center">';
	$output[] = '<tr><th>Item</th><th>Item Price</th><th>Quantity</th><th>Subtotal</th></tr>';
	foreach ($contents as $id=>$qty) {
		$sql = 'SELECT * FROM products WHERE Product_ID = '.$id;
		$result = $db->query($sql);
		$row = $result->fetch();
		extract($row);
		$output[] = '<tr>';
		$output[] = '<td align="center">'.$Common_Name.' ('.$Genus.')</td>';
 		$output[] = '<td>£'.$Price.'</td>';
		$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
		$output[] = '<td>£'.(($Price) * $qty).'</td>';
		$total += (($Price) * $qty);
		$output[] = '</tr>';
	}
	$output[] = '</table>';
	$output[] = '<h2 align="right">Total: £'.$total.'</h2>';
	$output[] = '</form>';
}
return join('',$output);
}

Link to comment
https://forums.phpfreaks.com/topic/187129-creating-a-sum-of-values/
Share on other sites

Doing it within the loop makes the most sense. But, that code could be made more efficient. You should never do loops within a query unless there is no other way.

 

Here's an example of changes I would make (not tested)

function printCart() {
   global $db;
   $cart = $_SESSION['cart'];
   if ($cart) 
   {
      $contents = array_count_values ( explode(',', $cart) );
      $contentIDs = array_keys($contents);
      $grandTotal = 0;

      $output[] = '<form action="basket.php?action=update" method="post" id="cart">';
      $output[] = '<table width="600" align="center">';
      $output[] = '<tr><th>Item</th><th>Item Price</th><th>Quantity</th><th>Subtotal</th></tr>';

      $sql = "SELECT * FROM products WHERE Product_ID IN (" . implode(', ', $contentIDs) . ")";
      $result = $db->query($sql);

      while($product = $result->fetch() 
      {
         $lineItemTotal = (($Price) * $qty);
         $grandTotal += $lineItemTotal ;

         $output[] = '<tr>';
         $output[] = '<td align="center">'.$Common_Name.' ('.$Genus.')</td>';
         $output[] = '<td>£'.$Price.'</td>';
         $output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
         $output[] = '<td>£'.$lineItemTotal.'</td>';
         $output[] = '</tr>';
      }

      $output[] = '</table>';
      $output[] = '<h2 align="right">Total: £'.$grandTotal.'</h2>';
      $output[] = '</form>';
   }
   return join('\n', $output);
}

To be honest, I'm not really sure how your code works. I would like my code to be more efficient but have tried using the code you posted and had some problems. For instance I am getting an 'unexpected ;' message on the

while($product = $result->fetch()

line. I think I will have a look at this at some point but the main thing I want to get working is the sum of the quantity amounts, so will keep searching for a way to do this.

 

Thanks for your help!

To be honest, I'm not really sure how your code works. I would like my code to be more efficient but have tried using the code you posted and had some problems. For instance I am getting an 'unexpected ;' message on the

while($product = $result->fetch()

line. I think I will have a look at this at some point but the main thing I want to get working is the sum of the quantity amounts, so will keep searching for a way to do this.

 

Thanks for your help!

 

Or, you could simply remove the offending ';'....

If you are running queries within loops like that you will eventually start having pages that will timeout before loading. As for your initial request, I took it to mean you wanted the sum of all the line item totals. But, re-reading your post I think you mean you want to have the total of the number of line item units. If so, just follow the same process as you are using to get the total cost.

 

Here's a change to the code I provided. I did not test the code (as you are apparently using a class of some sort). But, I think I found what was missing. Your code required the use of extract() on the record array (many consider the use of that function as bad practice).

 

function printCart() {
   global $db;
   $cart = $_SESSION['cart'];
   if ($cart) 
   {
      $contents = array_count_values ( explode(',', $cart) );
      $contentIDs = array_keys($contents);
      $grandTotal = 0;
      $qtyTotal   = 0;

      $output[] = '<form action="basket.php?action=update" method="post" id="cart">';
      $output[] = '<table width="600" align="center">';
      $output[] = '<tr><th>Item</th><th>Item Price</th><th>Quantity</th><th>Subtotal</th></tr>';

      $sql = "SELECT * FROM products WHERE Product_ID IN (" . implode(', ', $contentIDs) . ")";
      $result = $db->query($sql);

      while($product = $result->fetch()) 
      {
         extract($product);
         $lineItemTotal = (($Price) * $qty);
         $grandTotal += $lineItemTotal;
         $qtyTotal   += $qty;

         $output[] = '<tr>';
         $output[] = "<td align=\"center\">{$Common_Name} ({$Genus})</td>";
         $output[] = "<td>£{$Price}</td>";
         $output[] = "<td><input type=\"text\" name=\"qty{$id}\" value=\"{$qty}\" size=\"3\" maxlength=\"3\" /></td>";
         $output[] = "<td>£{$lineItemTotal}</td>";
         $output[] = '</tr>';
      }

      $output[] = '</table>';
      $output[] = "<h2 align=\"right\">Total Price: £{$grandTotal}</h2>";
      $output[] = "<h2 align=\"right\">Total Qty: £{$qtyTotal}</h2>";
      $output[] = '</form>';
   }
   return join('\n', $output);
}

Thanks so much for your help on trying to improve my code!

 

Unfortunately I still have a problem with the code though. $qty is not showing at all for each entry. I have to admit this is all going slightly over my head as I am trying to help a friend out with something. My previous experience in PHP was a good few years ago and all the different ways in which it is being used now confuse me a hell of a lot, so I am not really sure where to start with sorting this out!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.