Counting (total) of column in DB
Posted: Wed Jun 11, 2003 12:27 am
An easy one. A query that returns a sum of all values (INT) of a single column (total of a shopping cart) ?. Thx.
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
<?php
$totalrow = "SELECT price FROM cart"; # column that holds the prices of items in cart
$total = mysql_query($totalrow) or die(mysql_error());
$sumtotal = mysql_fetch_array($total);
$sum = array_sum($sumtotal);
echo $sum;
?>Code: Select all
<?php
$totalrow = "SELECT price FROM cart"; # column that holds the prices of items in cart
$total = mysql_query($totalrow) or die(mysql_error());
$sum = 0;
while ($row = mysql_fetch_assoc($total) {
$sum += $row['price'];
}
echo $sum;
?>Code: Select all
<?php
$sql = "SELECT SUM(price) AS price FROM cart";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$sum = $row['price'];