Jump to content

Add up weights of selected items


dachshund

Recommended Posts

Is it possible to add up a bunch of selected rows?

 

For example, something like this:

 

$sql = "SELECT (and add up) weight FROM store WHERE id LIKE $id" (there are multiple $id's)

 

Obviously that isn't the answer - but hopefully it gives an idea of what I'm after.

 

Thanks

 

Jack

Link to comment
https://forums.phpfreaks.com/topic/252788-add-up-weights-of-selected-items/
Share on other sites

this is what i've tried but it's not quite working

 


<?php
				$basket = $_SESSION['basket'];
				if ($basket) {
				$items = explode(',',$basket);
				$contents = array();
				foreach ($items as $item) {
				$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
				}
				foreach ($contents as $id=>$qty) {
				$totalweight = mysql_query("SELECT SUM(weight) FROM store WHERE id LIKE '$id'");
				echo $totalweight;
				}
				}
				?>

Better to use one query rather than in a loop like you did.

 

$ids = array_keys($contents);
$sql = 'SELECT id, SUM(weight) as weight FROM store WHERE id IN ('.implode(',', $ids).') GROUP BY id';
$res = mysql_query($sql);
$weights = array();
while ($row=mysql_fetch_assoc($res)){
   $weights[$row['id']] = $row['weight'];
}

$totalweight=0;
foreach ($contents as $id=>$qty){ 
  $totalweight += $weights[$id] * $qty;
}

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.