Step 3 - Database Abstraction with PEAR
While it is entirely possible to build a database abstraction layer from scratch, the PEAR libraries for PHP are well-tested and documented modules that can be used as building blocks. In particular, the PEAR DB library is a collection of database code that creates a single OOP interface to any DBMS database. By using the PEAR DB library, the application will be able to use a single interface with MySQL, ODBC, Informix, PostgreSQL, Microsoft SQL, Oracle, InterBase and Sybase databases. To use the PEAR DB library, extract the DB package to a PEAR directory and make sure that this path is included in your PHP configuration file as follows:
include_path=".;C:\Program Files\php\pear"
Now that PHP has access to the PEAR libraries, you include the DB.php file in your application using the require_once() directive as shown here:
require_once 'DB.php';
To establish a connection with PEAR DB, a data source name needs to be specified using the following syntax:
phptype(dbsyntax)://uid:pwd@protocol
+hostspec/database?option=value
Thus, to create a MySQL connection you would use something like this:
crequire_once 'DB.php';
$user = 'trainingUser';
$pass = 'qpwo1029';
$host = 'localhost';
$db_name = 'onlineTraining';
$dsn = "mysql://$user:$pass@$host/$db_name";
The last line of this code can be changed to represent the database interface to be used. For instance, the PHP5 mysqli interface can be used in place of the mysql type shown above. Alternatively, any of the following may also be used:
dbase -> dBase
fbsql -> FrontBase (functional since DB 1.7.0)
ibase -> InterBase (functional since DB 1.7.0)
ifx -> Informix
msql -> Mini SQL (functional since DB 1.7.0)
mssql -> Microsoft SQL Server
oci8 -> Oracle 7/8/9
odbc -> ODBC (Open Database Connectivity)
pgsql -> PostgreSQL
sqlite -> SQLite
sybase -> Sybase
With the database connection configured, connecting to the database is performed using the DB::connect() function.
$db = DB::connect($dsn);
if (DB::isError($db)) {
die ($db->getMessage());
}