0

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!

2

4 Answers 4

1

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 ....

Sign up to request clarification or add additional context in comments.

Comments

1

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'];

Comments

0

use

select sum(field) as sum

and

ttl_food['sum'];

Comments

0

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']);

1 Comment

You answer is not right. $ttl_food[$i]['sum'] is not right. It must be $ttl_food['sum'].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.