2013-06-04 35 views
2

我有這樣的代碼取得到結果只有一個

$sql = new PDO('mysql:host=localhost;dbname=b','root','root'); 
$f = $sql->query('select * from user'); 
$sql->setFetchMode(PDO::FETCH_ASSOC); 

while($row = $f->fetch()){ 
    print_r($row); 
} 

輸出是

Array 
(
    [id] => 1 
    [name] => turki 
    [mail] => ablaf 
    [pass] => 144 
) 
Array 
(
    [id] => 2 
    [name] => wrfwer 
    [mail] => fwerf 
    [pass] => werf 
) 

,這就是我真正想要的。但是,如果我這樣做

<?php 

$sql = new PDO('mysql:host=localhost;dbname=b','root','root'); 
$f = $sql->query('select * from user'); 
$f->setFetchMode(PDO::FETCH_ASSOC); 
print_r($f->fetch()); 
?> 

輸出是

Array 
(
    [id] => 1 
    [name] => turki 
    [mail] => ablaf 
    [pass] => 144 
) 

它有一個結果,但我有表中的兩行;這是爲什麼?

+1

取指曾經是在同一時間讀取一行。您可以使用fetch in loop或用戶fetchAll像其他說法來獲取所有行。 –

回答

5

取應當用於顯示數據庫結果下一行

爲了得到你應該使用fetchAll()所有行;

陣列更改您的例子:

<?php 
$sql = new PDO('mysql:host=localhost;dbname=b','root','root'); 
$f = $sql->query('select * from user'); 
$f->setFetchMode(PDO::FETCH_ASSOC); 
print_r($f->fetchAll()); 
?> 

或如果您要使用PDOStatement::fetch

<?php 
$sql = new PDO('mysql:host=localhost;dbname=b','root','root'); 
$f = $sql->query('select * from user'); 
while($row = $sth->fetch(PDO::FETCH_ASSOC)) 
{ 
    print_r($row); 
} 
?> 
2

在這種情況下使用fetchAll

$result = $f->fetchAll(); 
print_r($result); 
0

PDOStatement對象:只獲取從PDOStatement對象對象檢索一個記錄(無論它的指針),這就是爲什麼你必須遍歷獲取

0

的fetch()方法只返回一個記錄,並設置內部指針指向下一條記錄。你期望從這個方法中不能返回。

也許嘗試像使用fetchall不同的方法:

http://php.net/manual/en/pdostatement.fetchall.php

<?php 
$sth = $dbh->prepare("SELECT name, colour FROM fruit"); 
$sth->execute(); 

/* Fetch all of the remaining rows in the result set */ 
print("Fetch all of the remaining rows in the result set:\n"); 
$result = $sth->fetchAll(); 
print_r($result); 
?> 
0

$ F->取()內部結果的指針移動到下一個值(如果存在)這就是爲什麼你會得到一切在while()中調用它時的值。

0

$f->fetch() - 將得到行

$f->fetchAll() - 將得到所有

相關問題