2011-11-16 123 views
4

我創建了一個sqlite3的數據庫和PHP:PHP查詢只返回第一行

$db = new SQLite3('mysqlitedb.db'); 
$db->exec('CREATE TABLE foo (bar STRING)'); 
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')"); 
$db->exec("INSERT INTO foo (bar) VALUES ('This is another test')"); 

,但是當我試圖讓所有行:

$result = $db->query('SELECT * FROM foo'); 
var_dump($result->fetchArray()); 

它只返回的第一行在分貝:

array(2) { [0]=> string(14) "This is a test" ["bar"]=> string(14) "This is a test" } 

我不知道爲什麼它沒有返回所有的行。

回答

6

您需要遍歷行。你只會得到當前行。

while($row=$result->fetchArray()){ 
    // Do Something with $row 
    print_r($row); 
} 

The PHP Manual有頁面

+1

要繼續爲什麼你必須這樣做......想象你有一個數百萬行的數據庫,每行有很多KB大小......考慮你需要多少內存一次加載整個表。 – mah

+0

@mah,看到一個服務器將所有內容加載到內存中會很有趣! –

+0

@MechSoftware謝謝,第一次潛入sqlite3。 – daraeman

1

fetchArray()一個很好的例子,只獲取結果的第一行。如果你想獲取額外的行,可以額外調用fetchArray(也許在一個循環中)。

0

在一個數組中返回所有結果的請求。在一個對象中獲得所有結果,讓它們通過數組入口分裂,然後不得不將它們放回到一個數組中,看起來很浪費。