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;
}
}
The
PDOStatement::fetchObjectmethod does what you want.You can use it like:
This will result in
$abeing an object of classmodelArea, equivalent to the code you give.