2012-09-04 76 views
0

我有這個PHP代碼:麻煩MySQL的結果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管理此查詢,我得到一個不錯的行看起來像:

total apple orange 
    5  3   2 

任何人都知道我是怎麼做錯了嗎? (除了我正在使用mysql_fetch_row的「邪惡」版本的事實)

非常感謝!

+2

「誰知道什麼是錯的?」 ---你爲什麼認爲這是錯的?提供您的代碼在一個單一的,而不是分裂。你執行兩次'mysql_fetch_array'嗎? – zerkms

+1

請嘗試移至[mysqli](http://php.net/manual/en/book.mysqli.php)或[pdo](http://au2.php.net/manual/en/book.pdo .PHP)。 mysql_ *已棄用。如果你正在從一本教授mysql_ *函數的書中學習,那是陳舊過時的。 – Ivo

回答

0

你需要重新分析自己在做什麼。你的SQL只會返回一行並帶有一些聚合結果,但是你似乎希望能夠迭代多行結果(由於你的while())。

你的sql做什麼以及你如何使用它是兩回事。

+1

非常真實,我明白你的意思。謝謝! –

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."; 
+5

你說簡化了,但我認爲這是一個難以閱讀的命令。 –

+0

這不漂亮,但它的作品!謝謝Kolink! ......只是在等着看有沒有人有一個整潔的方式。 –