Introduction - Fetch

Introduction - Fetch -- Fetching rows from the query

Description

Fetch functions

The DB_Result object provides two functions to fetch rows: fetchRow() and fetchInto(). fetchRow() returns the row, null on no more data or a DB_Error, when an error occurs. fetchInto() requires a variable, which be will directly assigned by reference to the result row. It will return null when result set is empty or a DB_Error too.

Select the format of the fetched row

The fetch modes supported are:

Set the format of the fetched row

You can set the fetch mode per result call or for your whole DB instance.

Fetch rows by number

The PEAR DB fetch system also supports an extra parameter to the fetch statement. So you can fetch rows from a result by number. This is especially helpful if you only want to show sets of an entire result (for example in building paginated HTML lists), fetch rows in an special order, etc.

Freeing the result set

It is recommended to finish the result set after processing in order to to save memory. Use free() to do this.

Quick data retrieving

DB provides some special ways to retrieve information from a query without the need of using fetch*() and loop throw results.

getOne() retrieves the first result of the first column from a query
$numrows = $db->getOne('select count(id) from clients');

getRow() returns the first row and returns it as an array.
$sql = 'select name, address, phone from clients where id=1';
if (is_array($row = $db->getRow($sql))) {
    list($name, $address, $phone) = $row;
}

getCol() returns an array with the data of the selected column. It accepts the column number to retrieve as the second parameter.
$all_client_names = $db->getCol('SELECT name FROM clients');
The above sentence could return for example:
$all_client_names = array('Stig', 'Jon', 'Colin');

getAssoc() fetches the entire result set of a query and return it as an associative array using the first column as the key.
$data = getAssoc('SELECT name, surname, phone FROM mytable')
/*
Will return:
array(
  'Peter'      => array('Smith', '944679408'),
  'Tomas' => array('Cox', '944679408'),
  'Richard' => array('Merz', '944679408')
)
*/

getAll() fetches all the rows returned from a query-
$data = getAll('SELECT id, text, date FROM mytable');
/*
Will return:
array(
   1 => array('4', 'four', '2004'),
   2 => array('5', 'five', '2005'),
   3 => array('6', 'six', '2006')
)
*/

The get*() family methods will do all the dirty job for you, this is: launch the query, fetch the data and free the result. Please note that as all PEAR DB functions they will return a DB_Error object on errors.

Getting more information from query results

With DB you have many ways to retrieve useful information from query results. These are:

Don't forget to check if the returned result from your action is a DB_Error object. If you get a error message like "DB_Error: database not capable", means that your database backend doesn't support this action.