supdown
supdown

Reputation: 33

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?

Upvotes: 2

Views: 6078

Answers (5)

Your Common Sense
Your Common Sense

Reputation: 157940

Just change the way you're calling fetchAll()

$rst = $stm->fetchAll(PDO::FETCH_CLASS, 'Product');

Upvotes: 1

SebCar
SebCar

Reputation: 338

You can use constructor arguments (http://php.net/manual/en/pdostatement.fetchall.php)

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

Note: properties must be public

Upvotes: 0

Danijel
Danijel

Reputation: 12709

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

Upvotes: 5

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23399

You have to write a method to do it.

class Product {
   $id;
   $name;
   public function loadData($data){
      $this->id = $data['id'];
      $this->name = $data['name'];
   }
}

$Product = new Product();
$Product->loadData($database_results);

Or, if you're going to be doing this for every object, use a constructor..

class Product {
   $id;
   $name;
   public function __construct($id, $pdo){
      $pdo->prepare("select * from table where id = :id");
      // do your query, then...
      $this->id = $data['id'];
      $this->name = $data['name'];
   }
}

$Product = new Product($id, $pdo);

Upvotes: 0

Scott G.
Scott G.

Reputation: 323

My approach in this case would be to use a helper function within the Product class that builds a new instance of the object and returns it provided the inputs from the PDO.

Such as

public static function buildFromPDO($data) {
    $product = new Product();
    $product->id = $data["id"];
    $product->name = $data["name"];

    return $product;
}

Then inside of your PDO call, loop through the return and array_push onto an array containing all your products built via this function.

$products = array();
foreach ($rst as $r) {
    array_push($products, Product::buildFromPDO($r));
}

You also might want to consider using an ORM if it seems like you'll be doing a ton of this kind of stuff.

Upvotes: 0

Related Questions