Php fetch in PDO只获得一个结果

Php fetch in PDO只获得一个结果,php,mysql,database,pdo,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] =&

我有这个密码

$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());
?>
它有一个结果,但我在表中有两行;为什么会这样?

在这种情况下,请使用


PDOStatement:fetch只从PDOStatement对象(无论其指针在何处)检索一条记录,这就是为什么必须循环fetch

fetch()方法只返回一条记录,并将内部指针设置为指向下一条记录。您期望此方法返回它无法返回的内容

或许可以尝试其他方法,如fetchAll:


$f->fetch()将内部结果指针移动到下一个值(如果存在),这就是为什么调用while()时会得到所有值的原因

Fetch应用于显示数据库结果的下一行

要获取您应该使用的所有行

  • -从结果集中获取下一行
  • -返回包含所有结果集行的数组
将示例更改为:

 <?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());
 ?>

或者如果你想用


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


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

用于一次获取一行的fetch。您可以使用fetch-in-loop或用户fetchAll来获取所有行。
$result = $f->fetchAll();
print_r($result);
<?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);
?>
 <?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());
 ?>
 <?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);
 }
 ?>