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:
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
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
Use $result = $q->fetchAll(PDO::FETCH_OBJ);