我有以下PHP代码:
$count = "select
count(fruit) as total,
sum(fruit like '%apple%') as apple,
sum(fruit like '%orange%') as orange
FROM my_wonderful_table_of_fruits";
$count = mysql_query($count);
$count = mysql_fetch_row($count);
我正在尝试将这些存储在变量中,似乎无法捕捉它们:/
我的代码是:
while ($row = mysql_fetch_array($count)) {
$count_total = $row['total'];
$count_apple = $row['apple'];
$count_orange = $row['orange'];
}
我希望能像这样回应他们:
echo "$count_total[0] is the total of $count_apple apples and $count_orange oranges
当我在MySQL Admin中运行此查询时,我得到了一个很好的行:
total apple orange
5 3 2
任何人都知道我做错了什么? (除了我正在使用'邪恶'版本的mysql_fetch_row)
非常感谢!
答案 0 :(得分:1)
由于您的查询只生成一行,您可以将其简化为以下内容:
list($total,$apple,$orange) = mysql_fetch_row(mysql_query("
SELECT COUNT(`fruit`) AS `total`,
SUM(`fruit` LIKE '%apple%') AS `apple`,
SUM(`fruit` LIKE '%orange%') AS `orange`,
FROM `my_wonderful_table_of_fruits`"));
echo "$total is the total of $apple apples and $orange oranges.";
答案 1 :(得分:0)
您需要重新分析您正在做的事情。您的SQL只返回一行包含一些聚合结果,但似乎您希望能够迭代几行结果(由于您的while()
)。
你的sql做了什么以及你如何使用它是两回事。