Jump to content

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;
}

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.