Reputation: 1
I was trying to calculate the total of each column in the database and display it on the webpage using php. But it just gives me
Array
(
[0] => 6
[sum(food1)] => 6
)
which I just want '6' as my result.
Here is my code
for($i=1; $i<=10; $i++){
$foodid=('food'."$i");
echo $foodid;
$food_query = mysql_query("select sum($foodid) from orderdetail where date between '$fm_date' and '$to_date'");
$ttl_food= mysql_fetch_array($food_query);
print_r($ttl_food[$i]);
}
Thanks so much!
Upvotes: 0
Views: 445
Reputation: 4282
Try this:
for($i=1; $i<=10; $i++){
$foodid=('food'."$i");
echo $foodid;
$food_query = mysql_query("select sum(field) as sum from orderdetail
where date between '$fm_date' and '$to_date'");
$ttl_food= mysql_fetch_array($food_query);
print_r($ttl_food['sum']);
Upvotes: 0
Reputation: 2758
Try below one by giving an alias
name sumoffood
to your aggregate function's output
$food_query = mysql_query("select sum($foodid) as sumoffood from orderdetail where date between '$fm_date' and '$to_date'");
and then use
$ttl_food= mysql_fetch_assoc($food_query);
echo $ttl_food['sumoffood'];
Upvotes: 1
Reputation: 4446
The result of SELECT SUM
or any other functions like COUNT()
, MAX()
etc. is always a recordset. You need to just take the first element of the array of rows (even if only one row exists). Just $your_rows_array[0]
.
To avoid having strange names like [sum(food1)]
you can SELECT SUM($foodid) AS mysum FROM ...
.
Upvotes: 1