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
https://forums.phpfreaks.com/topic/261415-sum-a-calculted-column/
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'];
}

 

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.