Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO PHP Fetch Class

Tags:

php

pdo

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 set BEFORE the constructor is called.What does this mean? Any direction is greatly appreciated.

like image 253
Aditya Shukla Avatar asked Feb 28 '11 00:02

Aditya Shukla


People also ask

What is fetch in PDO?

Fetches a row from a result set associated with a PDOStatement object. The mode parameter determines how PDO returns the row.

What is PDO class in PHP?

What is PDO? PDO - PHP Data Object. A set of PHP extensions that provide a core PDO class and database specific drivers. Provides a vendor-neutral lightweight data-access abstraction layer. Focus on data access abstraction rather than database abstraction.

What does fetch () do in PHP?

Introduction to the PHP fetch() method The fetch() method allows you to fetch a row from a result set associated with a PDOStatement object. Internally, the fetch() method fetches a single row from a result set and moves the internal pointer to the next row in the result set.


1 Answers

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 you 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.

like image 186
RobertPitt Avatar answered Oct 12 '22 02:10

RobertPitt