Jump to content

Sum a calculted column


nikster

Recommended Posts

I fairly new to PHP. This seems very obvious but I cannot find an answer.

 

O programmer friend of mine said that I should never store a calculated value in a table because it was redundant. SO I have a very simple shopping cart. In the confirmation email, I ask the database for the line items of the order. So I'm pulling the quantity and price from the database. In the email I created a var called $ext which is $price * $disc which works.  I cannot figure out how to total $ext.

 

I created a var called $subtotal. Heres the code.

 

$result = mysql_query("SELECT * FROM order_detail, products

WHERE $ordid = orderid AND

order_detail.productid = products.serial");

 

while($row = mysql_fetch_array($result))

{

$prodid = $row['productid'];

$qty = $row['quantity'];

$price = $row['price'];

$prodname = $row['name'];

$proddesc = $row['description'];

$ext = $qty * $price;

$subtotal = 0;

$subtotal = ($subtotal + $ext);

}

 

Any help would be appreciated.  :confused:

Link to comment
Share on other sites

You can either use the SUM function in mysql during the mysql_query, but by doing this, you won't get the other rows you want, just one, as it will group them.

$result = mysql_query("SELECT *, SUM(price) AS totalprice FROM order_detail, products
WHERE $ordid = orderid AND
order_detail.productid = products.serial");

^ May complain if you don't group by something. As I said, it will just return one row.

 

or you can add it together while you fetch the data:

$totalprice=0;
while($row = mysql_fetch_array($result))
{
   $prodid = $row['productid'];
   $qty = $row['quantity'];
   $price = $row['price'];
   $prodname = $row['name'];
   $proddesc = $row['description'];
   $ext = $qty * $price;
   $subtotal = 0;
   $subtotal = ($subtotal + $ext);
   $totalprice += $row['price'];
}

 

Link to comment
Share on other sites

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.