05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

$db = DB::connect($datasource);<br />

if (DB::isError($db)) {<br />

die($db->getMessage( ));<br />

}<br />

The DB::isError( ) method returns true if an error occurred while working with the<br />

database object. If there was an error, the usual behavior is to stop the program and<br />

display the error message reported by the getMessage( ) method. You can call<br />

getMessage( ) on any PEAR DB object.<br />

Issuing a Query<br />

The query( ) method on a database object sends SQL to the database:<br />

$result = $db->query(sql);<br />

A SQL statement that doesn’t query the database (e.g., INSERT, UPDATE, DELETE)<br />

returns the DB_OK constant to indicate success. SQL that performs a query (e.g.,<br />

SELECT) returns an object that you can use to access the results.<br />

You can check for success with DB::isError( ):<br />

$q = $db->query($sql);<br />

if (DB::iserror($q)) {<br />

die($q->getMessage( ));<br />

}<br />

Fetching Results from a Query<br />

PEAR DB provides two methods for fetching data from a query result object. One<br />

returns an array corresponding to the next row, and the other stores the row array<br />

into a variable passed as a parameter.<br />

Returning the row<br />

The fetchRow( ) method on a query result returns an array of the next row of results:<br />

$row = $result->fetchRow([ mode ]);<br />

This returns either an array of data, NULL if there is no more data, or DB_ERROR if an<br />

error occurred. The mode parameter controls the format of the array returned, which<br />

is discussed later.<br />

This common idiom uses the fetchRow( ) method to process a result, one row at a<br />

time, as follows:<br />

while ($row = $result->fetchRow( )) {<br />

if (DB::isError($row)) {<br />

die($row->getMessage( ));<br />

}<br />

// do something with the row<br />

}<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

PEAR DB Basics | 195

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!