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!
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 ...
.
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'];
use
select sum(field) as sum
and
ttl_food['sum'];
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']);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.