How to force PDOStatement->fetchAll to return array of objects?

后端 未结 3 628
孤街浪徒
孤街浪徒 2020-12-15 17:55

I am writing my own simply ORM using PDO. My question is if you can force PDOStatement::fetchAll() method to return array of objects of stdClass? For example:

3条回答
  •  遥遥无期
    2020-12-15 18:24

    This will do it:

     prepare("SELECT name, colour FROM fruit");
     $sth->execute();
    
     $result = $q->fetchAll(PDO::FETCH_OBJ);
     //$result contains an array of stdObjects
     ?>
    

    However even cooler way is to get PDO to instantiate your own class and populate the properties for you:

    Example #4 Instantiating a class for each result

    The following example demonstrates the behaviour of the PDO::FETCH_CLASS fetch style.

     prepare("SELECT name, colour FROM fruit");
     $sth->execute();
    
     $result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit");
     //$result contains an array of fruit objects
     ?>
    

    Source: http://www.php.net/manual/en/pdostatement.fetchall.php

提交回复
热议问题