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

后端 未结 3 601
孤街浪徒
孤街浪徒 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:07

    You should also be able to do the following:

    $stmt->setFetchMode(PDO::FETCH_OBJ); //set the mode for all fetch request
    

    With any subsequent fetch request you can omit explicitly specifying the mode.

    $stmt->setFetchAll(); //returns an array of objects
    
    0 讨论(0)
  • 2020-12-15 18:24

    This will do it:

     <?php
     $sth = $dbh->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.

     <?php
     class fruit {
         public $name;
         public $colour;
     }
    
     $sth = $dbh->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

    0 讨论(0)
  • 2020-12-15 18:28

    Use $result = $q->fetchAll(PDO::FETCH_OBJ);

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