How do I fetch mulitiple rows using fetch(PDO::FETCH_ASSOC) with pdo?

后端 未结 2 1623
生来不讨喜
生来不讨喜 2021-01-24 18:47

testQuery() is the method I use to get all rows from table CATEGORIES

public function __construct()
 {
 self::$tdb = Database::getConnection();
 }



 #mock quer         


        
相关标签:
2条回答
  • 2021-01-24 19:10

    Fetch does indeed pull the data from the database one at a time, but you need to iterate through the rows until you have all the data.

    You might want to pop this into a loop to get all the data:

    $stmtAA->fetch(PDO::FETCH_ASSOC);
    

    Something like this should do the trick:

    while($row=$this->prepared->fetch(PDO::FETCH_ASSOC))
    {
        $this->ID=$row['id'];
        $something=$row['something'];
    }
    

    Depending on if you are populating variables or have the code within an object.

    0 讨论(0)
  • 2021-01-24 19:21

    You could simply return the statement object.
    Or if you want to encapsulate it (so that it can only be used to fetch the data) use the SPL's IteratorIterator

    return new IteratorIterator($stmtAA);
    

    then you can use

    foreach( testQuery() as $row) { ... }
    

    in your script.

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