fetchall(PDO::FETCH_CLASS, 'modelClassName'); ...">

Pdo fetch object?

Is there a better way to return a db result object?

I know " return $statement->fetchall(PDO::FETCH_CLASS, 'modelClassName'); " but it only works on the 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; } } 
+6
source share
2 answers

The PDOStatement::fetchObject does what you want.

You can use it like:

 $a = $statement->fetchObject('modelArea'); 

This will cause $a be an object of class modelArea , equivalent to the code you give.

+15
source

You can 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); 
+1
source

Source: https://habr.com/ru/post/887302/


All Articles