我有以下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的"邪恶"版本之外)
非常感谢!
由于查询只生成一行,因此可以将其简化为以下内容:
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.";
您需要重新分析您正在做的事情。SQL只会返回一行,其中包含一些聚合结果,但您似乎希望能够迭代几行结果(由于while()
)。
sql的作用和使用方法是两回事。