Convert PDO resultset to array of objects

梦想与她 提交于 2020-07-19 06:48:10

问题


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?


回答1:


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




回答2:


Just change the way you're calling fetchAll()

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



回答3:


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.




回答4:


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);



回答5:


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



来源:https://stackoverflow.com/questions/32614808/convert-pdo-resultset-to-array-of-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!