Database Techniques and PHP - Issuing a Query (
Page 2 of 4 )
The query() method on a database object sends SQL to the database:
$result = $db->query(sql);
A SQL statement that doesn’t query the database (e.g.,
INSERT
,
UPDATE
,
DELETE
) returns the
DB_OK
constant to indicate success. SQL that performs a query (e.g.,
SELECT
) returns an object that you can use to access the results.
You can check for success with
DB::isError()
:
$q = $db->query($sql);
if (DB::iserror($q)) {
die($q->getMessage());
}
Fetching Results from a Query
PEAR DB provides two methods for fetching data from a query result object. One returns an array corresponding to the next row, and the other stores the row array into a variable passed as a parameter.
Returning the row
The fetchRow() method on a query result returns an array of the next row of results:
$row = $result->fetchRow([ mode ]);
This returns either an array of data, NULL
if there is no more data (or none to begin with—an empty result), or
DB_ERROR
if an error occurred. The
mode
parameter con
trols the format of the array returned, which is discussed later.
This common idiom uses the
fetchRow()
method to process a result, one row at a time, as follows:
while ($row = $result->fetchRow())
{
if (DB::isError($row)) {
die($row->getMessage());
}
// do something with the row
}
Storing the row
The fetchInto() method not only gets the next row, but also stores it into the array variable passed as a parameter:
$success = $result->fetchInto(array, [mode]);
Like
fetchRow()
,
fetchInto()
returns
NULL
if there is no more data, or
DB_ERROR
if an error occurs.
The idiom to process all results looks like this with
fetchInto()
:
while ($success = $result->fetchInto($row)) {
if (DB::isError($success)) {
die($success->getMessage());
}
// do something with the row
}