International Developer Logo Last Updated 27.08.08 at 11.48
On Sale
This months front cover, click to see the table of contents.
Subscribe
 
TUTORIALS

Developing Three-Tier Web Applications with PHP


Daniel Winter   01.10.05

A recordset is returned by the PEAR DB library as an ordered array by default. It is also possible to set the results to be returned as an associative array or an object. To set the connection object to return objects, DB_FETCHMODE_OBJECT can be passed to the fetchInto() function. Alternatively, this behaviour can be set as the default using the setFetchMode method of the connection object as shown here.

$db->setFetchMode(DB_FETCHMODE_OBJECT);

To iterate through a record set of objects, the fetchInto() method of the results object can be used within a while loop. Alternatively, a particular row can be retrieved by passing the index as the third parameter. To obtain information about the results, the numRows(), numCols() and affectedRows() functions can be invoked. The following example demonstrates a foreach loop that displays each id value of a recordset. The number of rows of the record set is determined using the numRows() method, and the loop index is used to select the desired row of the result within the loop.

$from = 1;
$to = $res->numRows();
foreach (range($from, $to) as $rowNum) {
    if (!$res->fetchInto($row, DB_FETCHMODE_OBJECT, $rowNum)) {
        break;
    }
    $resultArray[$rownum] = $row->id;
}

Alternatively, if you don't need to loop through each row to process the results, the entire record set can be assigned to an array as shown below. The getAll() method is particularly useful in this context as it creates an array that can be passed directly to the template engine for processing into HTML, but more on this in a moment.

$resultArray = $db->getAll($sql, DB_FETCHMODE_OBJECT);

Using the PEAR DB library you can abstract the database connectivity from your application with a level of portability that makes moving from one vendor to another a simple process. What it doesn't give you, however, is SQL abstraction. In other words, there will be no vendor specific code in your application layer, but there will be SQL statements. This is unsuitable if, for instance, you want to use stored procedures in MySQL or MS SQL Server. To provide this higher-level abstraction, a data interface layer will need to be built that completely obscures the SQL commands.




   Previous Page  1 2 3 4 5 6 7 8 9 10 ... Next Page   

HAVE YOUR SAY
This article is rated  Rate this article