HomePHP Page 4 - PHP Application Development With ADODB (part 1)
Anatomy Class - 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.
In order to demonstrate how the abstraction layer works, I'll use it to rewrite the previous example - take a look:
<?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 it 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 (!$result->EOF)
{
echo $result->fields[1] . " - " . $result->fields[2] . "\n";
$result->MoveNext();
}
// get and print number of rows in resultset
echo "\n[" . $result->RecordCount() . " rows returned]\n";
// close database connection
$db->Close();
?>
This output of this snippet is equivalent to that of the previous one;
however, since it uses the ADODB abstraction library, rather than PHP's native API, to interact with the database server, it holds out the promise of continuing to work no matter which database I use. I'll show you how in a minute - but first, a quick explanation of the functions used above:
1. The first step is, obviously, to include the abstraction layer in your script.
<?
// include the ADODB library
include("adodb.inc.php");
?>
Note that the ADODB library doesn't consist of just this file - in fact,
there are over thirty different files included with the library, many of them drivers for different databases. You don't need to worry about including each and every one; simply include the main class file, as above, and it will invoke the appropriate drivers or additional classes as required.
2. Next, create an instance of the ADODB class.
<?
// create an object instance
// configure library for a MySQL connection
$db = NewADOConnection("mysql");
?>
The parameter passed to the object constructor tells ADODB which type of
database you're trying to connect to. In this case, I've used the argument "mysql", since I'm going to be connecting to a MySQL database server; you could just as easily use "pgsql" or "oci8" or...
3. Next, it's time to open up a connection to the database. This is accomplished via the Connect() method, which must be passed a set of connection parameters.
<?
// open connection to database
$db->Connect("localhost", "john", "doe", "db278") or die("Unable to
connect!"); ?>
Reading this may make your head hurt, but there *is* method to the madness
- roughly translated, the line of code above attempts to open up a connection to the MySQL database named "db278", on the host named "localhost", with the username "john" and password "doe".
4. Once the Connect() method does its job, the object's Execute() method can be used to execute SQL queries on that database.
<?
// execute query
$query = "SELECT * FROM library";
$result = $db->Execute($query) or die("Error in query: $query. " .
$db->ErrorMsg()); ?>
Successful query execution returns a new object containing the results of
the query. Note the special ErrorMsg() method, which can be used to obtain the last error message generated by the system.
5. The result object returned in the previous step exposes methods and properties that can be used to extract specific fields or elements from the returned resultset.
<?
// iterate through resultset
// print column data in format TITLE - AUTHOR
while (!$result->EOF)
{
echo $result->fields[1] . " - " . $result->fields[2] . "\n";
$result->MoveNext();
}
?>
In this case, the object's MoveNext() method is used, in combination with
a "while" loop, to iterate through the returned resultset and display individual fields (these individual fields are accessed as array elements of the object's "fields" property). This data is then printed to the output device.
Once all the rows in the resultset have been processed, the object's RecordCount() method is used to print the number of rows in the resultset.
<?
// get and print number of rows in resultset
echo "\n[" . $result->RecordCount() . " rows returned]\n";
?>
6. Finally, with all the heavy lifting done, the Close() method is used to
gracefully close the database connection and disengage from the database.
<?
// close database connection
$db->Close();
?>
In the event that someone (maybe even me) decides to switch to a different
database, the only change required in the script above would be to the line instantiating the connection object - a new argument would need to be passed to the object constructor, with a new database type. Everything else would stay exactly the same, and my code would continue to work exactly as before.
This is the beauty of an abstraction layer - it exposes a generic API to developers, allowing them to write one piece of code that can be used in different situations, with all the ugly bits hidden away and handled internally. Which translates into simpler, cleaner code, better script maintainability, shorter development cycles and an overall Good Feeling. Simple, huh?