【问题标题】:PHP PDO SQL only returning one row of data instead of all rowsPHP PDO SQL 只返回一行数据而不是所有行
【发布时间】:2018-05-10 04:35:54
【问题描述】:

我正在使用 PHP PDO 扩展从数据库类别表中创建所有项目的列表。 预期结果不正确,只返回一行数据而不是全部 预期的行。 通过在 phpMyAdmin 控制台中运行相同的 SQL 语句,我得到了预期 所有数据行的结果。 我需要知道我用 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 
           )

【问题讨论】:

  • WHERE cat_parent_id = :catId
  • fetch()fetchAll()?前者返回一行,后者返回所有行。在循环中使用fetch

标签: php mysql pdo


【解决方案1】:

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

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

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

或创建一个循环,在其中不断调用PDOStatement::fetch(),直到它返回false

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

但后一个例子有点多余,如果你想一次获取所有行,除非你想解决一些内存问题。

【讨论】:

  • fetch() 太糟糕了!现在一切都按预期工作。感谢您的快速回复。
【解决方案2】:

你必须像下面这样使用 fetchAll:

$rows = $_stmt->fetchAll();
print_r($rows);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2015-05-05
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多