PDO PHP Fetch Class

后端 未结 4 1660
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 07:08

I am learning pdo in php , so as to make database access easier and more efficient .One explanation i have read for fetch _class is that The properties of your object are s

4条回答
  •  不知归路
    2020-11-28 07:41

    Instead of using: FetchAll(PDO::FETCH_CLASS, 'classname') You can use: fetchObject('classname')

    Example:

    class Car extends DatabaseTable {
    
    const TABLE_NAME = 'cars';
    
    // Table Columns
    private $color;
    private $brand;
    private $type;
    
    public function __construct($pdo, $id = false)
    {
        parent::__construct($pdo, TABLE_NAME, $id);
    }
    
    public static function getAll($pdo, $order = 'id') {
        $query =   'SELECT * FROM ' . self::TABLE_NAME . ' 
                    ORDER BY ' . $order;
    
        $statement = $pdo->prepare($query);
    
        $objects = [];
        while ($obj = $statement->fetchObject(self::class, [$pdo])) {
            $objects[$obj->getId()] = $obj;
        }
        return $objects;
    }
    

    The parent Constructor just sets its 3 properties like: $this->id = $id;

提交回复
热议问题