Is there a better way to return object of db result?
I am a aware "return $statement->fetchall(PDO::FETCH_CLASS, 'modelClassName');" but it only work on fetchall function?
class modelArea extends Model {
    public $areaID;
    public $postcode;
    public static function find($condition, $parameters) {
        $query = "SELECT * FROM area WHERE " . $condition;
        $statement = self::getDb()->prepare($query);
        if (!$statement->execute($parameters))
            return false;
        $query = $statement->fetch(PDO::FETCH_ASSOC);
        $a = new modelArea();
        $a->areaID = $query['areaID'];
        $a->postcode = $query['postcode'];
        return $a;
    }
}
                PDO::FETCH_ASSOC. Returns an array indexed by column name as returned in your result set. PDO::FETCH_BOTH (default) Returns an array indexed by both column name and 0-indexed column number as returned in your result set.
Protected Denomination of Origin: a geographical indication defined within European Union law in order to protect regional agricultural products and foodstuffs. Collins English Dictionary. Copyright © HarperCollins Publishers.
The PDO class ¶Represents a connection between PHP and a database server.
The PDOStatement::fetchObject method does what you want.
You can use it like:
$a = $statement->fetchObject('modelArea');
This will result in $a being an object of class modelArea, equivalent to the code you give.
You could create a static method of the modelArea class (or a separate factory class) and call:
modelArea::createFromArray($query);
or even have one that returns an array of modelArea objects
modelArea::createFromStatement($stmt);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With