Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pdo fetch object?

Tags:

php

pdo

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;
    }
}
like image 337
user622378 Avatar asked May 04 '11 17:05

user622378


People also ask

How do I use PDO fetch Assoc?

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.

What do you mean by PDO?

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.

What is PDO class in PHP?

The PDO class ¶Represents a connection between PHP and a database server.


2 Answers

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.

like image 151
Jon Avatar answered Oct 22 '22 01:10

Jon


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);
like image 43
James C Avatar answered Oct 22 '22 00:10

James C