nikster Posted April 22, 2012 Share Posted April 22, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/261415-sum-a-calculted-column/ Share on other sites More sharing options...
MMDE Posted April 22, 2012 Share Posted April 22, 2012 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']; } Quote Link to comment https://forums.phpfreaks.com/topic/261415-sum-a-calculted-column/#findComment-1339567 Share on other sites More sharing options...
nikster Posted April 22, 2012 Author Share Posted April 22, 2012 THAT'S IT!! My mistake was I had to declare the $subtotal var BEFORE the while($row = mysql_fetch_array($result) Thank you so much MMDE. Quote Link to comment https://forums.phpfreaks.com/topic/261415-sum-a-calculted-column/#findComment-1339578 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.