PDO PHP Fetch Class

This means that when using PDO to return a result into a custom object, you are required to set out the member variables which correspond to the query result keys.

such as:

class User
{
    //Predefine Here
    public $id;
    public $username;
    public $password;
    public $email;
    public $hash;

    public function profileLink()
    {
         return sprintf('<a href="/profile/%s">%s</a>',$this->id,$this->username);
    }
}

$result = $sth->fetchAll(PDO::FETCH_CLASS, "User");
foreach($result as $user)
{
    echo $user->profileLink();
}

This way PDO can set the variables to the object outside of its internal scope.

if your user class was like so:

class User
{
}

then PDO Would not be able to set the values from outside the scope, as there are no properties defined.

Leave a Comment