PHP Application Development With ADODB (part 1) - Different Strokes (
Page 5 of 10 )
ADODB also offers a number of
alternative methods to process a resultset. For example, you can retrieve the
resultset as a string-indexed associative array, where the keys are field names
and the values are the corresponding field values. Consider the following
example, which demonstrates:
<?php
// uncomment this to see plaintext output in your browser
// header("Content-Type: text/plain");
// include the ADODB library
include("adodb.inc.php");
// create an object instance
// configure library for a MySQL connection
$db = NewADOConnection("mysql");
// open connection to database
$db->Connect("localhost", "john", "doe", "db278") or die("Unable to
connect!");
// get resultset as associative array
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
// execute query
$query = "SELECT * FROM library";
$result = $db->Execute($query) or die("Error in query: $query. " .
$db->ErrorMsg());
// iterate through resultset
// print column data in format TITLE - AUTHOR
while (!$result->EOF)
{
echo $result->fields['title'] . " - " .
$result->fields['author'] . "\n";
$result->MoveNext();
}
// get and print number of rows in resultset
echo "\n[" . $result->RecordCount() . " rows returned]\n";
// close database connection
$db->Close();
?>
In this case, the value of the special $ADODB_FETCH_MODE variable tells
ADODB how the resultset should be structured.
You can also fetch each row
as an object, whose properties correspond to the field names, via ADODB's
FetchNextObject() method.
<?php
// uncomment this to see plaintext output in your browser
// header("Content-Type: text/plain");
// include the ADODB library
include("adodb.inc.php");
// create an object instance
// configure library for a MySQL connection
$db = NewADOConnection("mysql");
// open connection to database
$db->Connect("localhost", "john", "doe", "db278") or die("Unable to
connect!");
// execute query
$query = "SELECT * FROM library";
$result = $db->Execute($query) or die("Error in query: $query. " .
$db->ErrorMsg());
// iterate through resultset
// print column data in format TITLE - AUTHOR
while ($row = $result->FetchNextObject())
{
echo $row->TITLE . " - " . $row->AUTHOR . "\n";
}
// get and print number of rows in resultset
echo "\n[" . $result->RecordCount() . " rows returned]\n";
// close database connection
$db->Close();
?>
Note that this FetchNextObject() method automatically moves to the next
row in the resultset, and does not require an explicit call to MoveNext(). Once
the end of the resultset is reached, the method returns false.