PHP PDO SQL仅返回一行数据,而不是所有行 [英] PHP PDO SQL only returning one row of data instead of all rows

查看:172
本文介绍了PHP PDO SQL仅返回一行数据,而不是所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP PDO扩展来创建数据库类别表中所有项目的列表. 预期结果不正确,仅返回一行数据,而不是全部 预期的行数. 通过在phpMyAdmin控制台中运行相同的SQL语句,我得到了预期的结果 所有数据行的结果. 我需要知道我对pdo的看法.

I am using PHP PDO extension to create a list of all items from a DB category table. The expected results are not correct, only one row of data returned instead of all rows which is expected. By running the same SQL statement within the phpMyAdmin console I get the expected results for all rows of data. I need to know what I am overlooking with pdo.

当前代码:

    $catId = 0;   

    $sql = "SELECT *
            FROM category
            WHERE cat_parent_id = :catId
            ORDER BY cat_name";

    $_stmt = $this->_dbConn->prepare($sql);
    $_stmt->bindParam(":catId", $catId, PDO::PARAM_INT);  
    $_stmt->execute();

    $rows = $_stmt->fetch(PDO::FETCH_ASSOC);    

    // display PDO result - only getting one row instead of all rows.       
    print_r($rows);

    Array ( [cat_id] => 3 
            [cat_parent_id] => 0 
            [cat_name] => Shop 
            [cat_description] => Seminars 
            [cat_image] => c72e.gif 
            )

    // NOTE: By running the same SQL within the phpMyAdmin 
    // console I get the expected results with all rows.
    Array ( [cat_id] => 3 
            [cat_parent_id] => 0 
            [cat_name] => Shop 
            [cat_description] => Seminars 
            [cat_image] => c72e.gif 
           ),
          ( [cat_id] => 1 
            [cat_parent_id] => 0 
            [cat_name] => Site Map 
            [cat_description] => List content links 
            [cat_image] => c83b.gif 
           )

推荐答案

PDOStatement::fetch() 一次只会返回1行.

PDOStatement::fetch() will only return 1 row at a time.

您可以使用 PDOStatement::fetchAll() :

You could use PDOStatement::fetchAll():

$rows = $_stmt->fetchAll(PDO::FETCH_ASSOC);

或创建一个循环,在该循环中您继续调用PDOStatement::fetch()直到返回false:

or create a loop where you keep calling PDOStatement::fetch() until it returns false:

$rows = array();
while( $row = $_stmt->fetch(PDO::FETCH_ASSOC) ) {
  $rows[] = $row;
}

但是,如果您想一次获取所有行,除非您要解决一些内存问题,否则后一个示例有点多余.

But the latter example is a bit redundant, if you want to get all rows at once anyway, unless there are some memory concerns you want to address.

这篇关于PHP PDO SQL仅返回一行数据,而不是所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆