【问题标题】:'fetch' in PDO gets only one result [duplicate]PDO中的“获取”只得到一个结果[重复]
【发布时间】:2013-05-30 17:49:51
【问题描述】:

我有这个代码:

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

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

【问题讨论】:

  • fetch 曾经一次获取一行。您可以使用 fetch in loop 或 user fetchAll 像其他人说的那样来获取所有行。

标签: php mysql database pdo


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    在这种情况下使用fetchAll

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

    【讨论】:

      【解决方案3】:

      PDOStatement::fetch 只从 PDOStatement 对象(无论它的指针在哪里)中检索一条记录,这就是为什么您必须遍历 fetch .

      【讨论】:

        【解决方案4】:

        fetch() 方法只返回一条记录,并将内部指针设置为指向下一条记录。您期望从这个方法中得到它不能返回的东西。

        也许可以尝试不同的方法,例如fetchAll

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

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            【解决方案6】:

            $f-&gt;fetch() - 将获得一个

            $f-&gt;fetchAll() - 将获得所有

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-06-01
              • 2020-12-28
              • 2018-05-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多