HomePHP Page 7 - PHP Application Development With ADODB (part 1)
Playing The Field - PHP
PHP comes with a different API for different database types -whcih usually means a code rewrite every time your databaseadministrator decides to experiment with something new. But fear not -help is at hand, in the unlikely form of ADODB, a powerful databaseabstraction library for PHP applications.
ADODB comes with a number of utility functions that provide you with useful information on the query you just executed. The most useful of these are the RecordCount() and FieldCount() methods, which return the number of rows and columns in the recordset respectively. Here's a simple 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!");
// execute query
$query = "SELECT * FROM library";
$result = $db->Execute($query) or die("Error in query: $query. " .
$db->ErrorMsg());
// get and print number of rows in resultset
echo $result->RecordCount() . " rows returned\n";
// get and print number of fields in resultset
echo $result->FieldCount() . " fields returned\n";
// clean up
$db->Close();
?>
You can obtain further information on each field with the FetchField()
method, which returns an object containing detailed information on the field properties, including its name and type. Consider the following variant of the example above, which might make this a little clearer:
<?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());
// get field information
for($x=0; $x<$result->FieldCount(); $x++)
{
print_r($result->FetchField($x));
}
// clean up
$db->Close();
?>
Here's what the output might look like for the "id" field: