1

want from a method return an array of objects, what is the best way retrieving data from the db and then populate a list of objects to be returned.

       <?php

        class DataObject{
          public function GetObjetList(){
           // Connect to the database server
           $dbh = new PDO("mysql:host=localhost;dbname=bookdb", "webuser", "secret");
           // Execute the query return 1200 register
           $stmt = $dbh->query('SELECT sku, title FROM products ORDER BY title');
           while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $sku = $row['sku'];
                $title = $row['title'];
                return something?? --> how to??
          }
        }
       ?>

regards!

MauricioHz
  • 111
  • 2
  • 12

3 Answers3

2

PDO already has a fetch mode that returns objects.

Change your code to this:

while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
silkfire
  • 24,585
  • 15
  • 82
  • 105
-1
class DataObject
{
    public function __construct($pdo)
    {
        $this->db = $pdo;
    }
    public function GetObjetList()
    {
        $sql = 'SELECT sku, title FROM products ORDER BY title';
        return $this->db->query($sql)->fetchAll(PDO::FETCH_OBJ);
    }
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
-2

Put the return after the while, not inside, use FETCH_OBJ and an array:

     $rows = array();
     $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
     return $rows;
Daniel W.
  • 31,164
  • 13
  • 93
  • 151