Using PDO::fetchAll – Examples with codes and output results

 

PHP Data Objects (PDO) as an abstraction layer used for accessing databases. It makes life easier while working with databases oriented applications.
There are several fetch modes available with the library which help us through the development and it would reduce a lot of custom coding if we know exactly how to use them.

We will discuss some of them.

  • PDO::FETCH_COLUMN
  • PDO::FETCH_ASSOC
  • PDO::FETCH_BOTH
  • PDO::FETCH_KEY_PAIR
  • PDO::FETCH_GROUP
  • PDO::FETCH_CLASS
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::fetchAll — Returns an array containing all of the result set rows

 

 

PDO::FETCH_COLUMN

Returns the indicated 0-indexed column.

Example result:

Sample code:

 

PDO::FETCH_ASSOC

returns an array indexed by column name as returned in your result set

Example result:

Sample code:

 

PDO::FETCH_BOTH

Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.

Example result:

Sample code:

 

PDO::FETCH_KEY_PAIR

Fetch a two-column result into an array where the first column is a key and the second column is the value

Example result:

Sample code:

 

PDO::FETCH_GROUP

Groups the result by the first column.

Example result:

Sample code:

 

PDO::FETCH_CLASS

Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class.

Sample code:

Example result:

 

Leave a Reply

Your email address will not be published. Required fields are marked *


*

Please wrap all source codes with [code][/code] tags.