0

我试图计算数据库中每一列的总数,并使用 php 将其显示在网页上。但它只是给了我

Array
(
    [0] => 6
    [sum(food1)] => 6
)

我只想要'6'作为我的结果。

这是我的代码

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

非常感谢!

4

4 回答 4

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'];
于 2013-05-17T10:20:55.037 回答
1

的结果SELECT SUM或任何其他函数(如COUNT()MAX())始终是记录集。您只需要获取行数组的第一个元素(即使只存在一行)。只是$your_rows_array[0]

为了避免像[sum(food1)]你一样有奇怪的名字SELECT SUM($foodid) AS mysum FROM ...

于 2013-05-17T10:17:41.947 回答
0

利用

select sum(field) as sum

ttl_food['sum'];
于 2013-05-17T10:16:44.880 回答
0

尝试这个:

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']);
于 2013-05-17T10:17:51.010 回答