在PDO中获取只获得一个结果

时间:2013-06-04 10:56:00

标签: php mysql database pdo

我有这段代码

$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
)

它有一个结果,但我在表中有两行;那是为什么?

6 个答案:

答案 0 :(得分:5)

应该使用Fetch来显示数据库结果的下一行

要获取所有行,请使用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);
 }
 ?>

答案 1 :(得分:2)

在这种情况下,请使用fetchAll

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

答案 2 :(得分:0)

PDOStatement:fetch只从PDOStatement对象中检索一条记录(无论指针在哪里),这就是你必须循环获取的原因

答案 3 :(得分: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);
?>

答案 4 :(得分:0)

$ f-&gt; fetch()将内部结果指针移动到下一个值(如果存在),这就是为什么在while()中调用它时获取所有值的原因;

答案 5 :(得分:0)

$f->fetch() - 将获得 1

$f->fetchAll() - 将获得所有

相关问题