Skip to content
Advertisement

Convert PDO resultset to array of objects

I have a PHP class called Product:

class Product {

   $id;
   $name;

}

And another class that get data from database:

$stm = $this->dsn->prepare($sql);

$stm->execute();

$rst = $stm->fetchAll(PDO::FETCH_ASSOC);

How can I convert this PDO resultset ($rst) to an array of objects Product?

Advertisement

Answer

Use the PDO::FETCH_CLASS argument.

class Product {
    public $id;
    public $name;
}

$stm = $this->dsn->prepare($sql);
$stm->execute();

$result = $stm->fetchAll( PDO::FETCH_CLASS, "Product" );

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement