2013-06-04 101 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() - 将得到所有