ADOdb - PHP Database Abstraction
August 27, 2005
Anyone who has used more than one database (MySQL, PostgreSQL, SQL Server, Oracle, etc) with PHP realizes it is cumbersome. In fact the developers of PHP have recently realized this as well. In 5.1 they are planning to include PHP Data Objects (PDO). However, in the meantime I recommend ADOdb.
Unfortunately, PHP's database access functions are not standardised. Every database extension uses a different and incompatibile API. This creates a need for a database class library to hide the differences between the different databases (encapsulate the differences) so we can easily switch databases.
Example connection to mySQL:
-
$db = NewADOConnection('mysql'); // type of connection
-
$db->SetFetchMode(ADODB_FETCH_ASSOC); // sets the query results to come back as assoc arrays
-
$db->PConnect('mysql_db_host', 'some_user', 'some_pass', 'the_db'); // make the connection
Example connection to Oracle:
-
<?php
-
$db = NewADOConnection('oci8'); // type of connection
-
$db->SetFetchMode(ADODB_FETCH_ASSOC); // sets the query results to come back as assoc arrays
-
$db->PConnect('oracle_db_host', 'jpseudo', 'his_password', 'oracle_sid'); // make the connection
-
?>
Comparing the two examples it's clear how similar connecting to either database becomes. Also notice we're setting the fetch mode to associative so we get back friendly associative arrays. The following is an example of how to query and get back results:
-
<?php
-
$query = "SELECT * FROM tablename";
-
$res = $db->Execute($query);
-
while($row = $res->FetchRow())
-
{
-
// $row is an associative array, indexed by fieldname from the table
-
}
-
?>
This will get back a bunch of rows of data, You might want less, like a single row or single field of a single row.
-
<?php
-
$row = $db->GetRow("SELECT * FROM tablename WHERE id_field='single_value'"); // this returns an associative array of the single row
-
$a_field = $db->GetRow("SELECT a_field FROM tablename WHERE id_field='single_value'"); // this returns the value of single field of the single row
-
?>
More Resources:
ADOdb Database Abstraction Library for PHP Main Site
ADOdb Documentation
Alternate Abstraction Library: PEAR DB
Tags: adodb, database, database abstraction, databases, mysql, oracle, pdo, php, programming
Comments
One Response to “ADOdb - PHP Database Abstraction”
Got something to say?

Thanks… for those interested, I did a benchmark of PDO and the ADOdb library on my site.