PHP PDO SQL only returning one row of data instead of all rows

后端 未结 2 400
野趣味
野趣味 2020-12-20 10:10

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

相关标签:
2条回答
  • 2020-12-20 10:47

    You have to use fetchAll like below:

    $rows = $_stmt->fetchAll();
    print_r($rows);
    
    0 讨论(0)
  • PDOStatement::fetch() will only return 1 row at a time.

    You could use PDOStatement::fetchAll():

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

    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.

    0 讨论(0)
提交回复
热议问题