MySQL选择查询中只返回1行

时间:2014-08-01 07:17:28

标签: php mysql pdo

为什么当我在使用PDO的MySQL数据库中使用select查询时它只返回1行,而实际上我需要它呢?

这是我的代码

    $data= $connectionStrings->prepare("SELECT * FROM animals");
    $data->execute();
    $information = $data->fetch();
    return $information;

3 个答案:

答案 0 :(得分:1)

您的代码:

    $data= $connectionStrings->prepare("SELECT * FROM country");
    $data->execute();
    $information = $data->fetch();
    return $information;

如果你想要返回它们全部使用$data->fetchAll();,但是,如果你返回一个大的结果集,它可能会导致你的应用程序崩溃或非常慢。

通过在循环中使用fetch(),您可以一次处理一行返回的数据,以减轻压力:

while ($row = $data->fetch()) {
 //handle $row
}

答案 1 :(得分:0)

这是因为你使用的是fetch()而不是fetchAll()

    $data= $connectionStrings->prepare("SELECT * FROM animals");
    $data->execute();
    $information = $data->fetchAll();
    return $information;

在此处阅读更多内容:http://php.net/manual/en/pdostatement.fetchall.php

答案 2 :(得分:0)

http://php.net/manual/en/pdostatement.fetchall.php获取所有结果。应该多次调用fetch()。这是因为查询的结果可能很大,并且一次将所有内容加载到内存中并不聪明。取决于当然的背景。