Hudzilla.org - the homepage of Paul Hudson
Contents > Databases Wish List | Report Bug | About Me ]

9.6     PEAR::DB

This is NOT the latest copy of this book; click here for the latest version.

PEAR::DB is an advanced, object-oriented database library that provides full database abstraction - that is, you use the same code all your databases. If you want your code to be as portable as possible, PEAR::DB provides the best mix of speed, power, and portability. However, if your scripts are only ever going to run locally, there is no real compelling reason to use PEAR::DB.

PEAR::DB works by abstracting not only the calls neccessary to work with the databases (such as mysql_connect(), pgsql_query(), etc), but also clashes in SQL syntax, such as the oft-argued "LIMIT" clause. In PHP 5.1 there's a new extension called PHP Data Objects (PDO) that abstracts only the functions, which gives a half-way house between PEAR::DB and just using normal DB calls. PEAR::DB is likely to be updated to use PDO, as it's a great deal more efficient.

This script below provides a good demonstration of how PEAR::DB works:

<?php
    
include_once('DB.php');

    
$conninfo = "mysql://username:password@localhost/phpdb";
    
$db = DB::connect($conninfo);
    
    if (
DB::isError($db)) {
        print
$db->getMessage();
        exit;
    } else {
        
$result = $db->query("SELECT * FROM people;");

        while (
$result->fetchInto($row, DB_FETCHMODE_ASSOC)) {
            
extract($row);
            print
"$Name: $NumVisits\n";
        }
    
        
$result->free();
    }
    
    
$db->disconnect();
?>

Notice how PEAR::DB uses a URL-like connection string, often called a Data Source Name (DSN), to entirely define its connection. This is the same method as seen in JDBC, so it should be familiar to Java developers already. The string can be broken down like this:

mysql://

Connection type

Username

Your username

Password

Your password

@localhost

The address of your server

/phpdb

The database name to use

The connection type is for what kind of server to which you intend on connecting. You can choose from the following list:

fbsql

FrontBase

ibase

InterBase

ifx

Informix

msql

Mini SQL

mssql

Microsoft SQL Server

mysql

MySQL

oci8

Oracle 7/8/8i

odbc

ODBC (Open Database Connectivity)

pgsql

PostgreSQL

sqlite

SQLite

sybase

SyBase

The rest of the string is quite straightforward, so you should now be able to fashion a DSN for your own system. Continuing on with the code, once the DSN is prepared, it is simply a matter of passing it into a call to DB::connect() as its first parameter - this will return a reference to the object we can use for querying. Remember that PEAR::DB is object-oriented, which means you need to hang on to the return value from DB::connect().

DB::isError() is a special function call that takes one parameter, the value to check, and returns true if that value is one of PEAR::DB's error types. Here $db is passed in, because if DB::connect() failed, it would return an error message that is picked up by DB::isError(). In the off-chance that an error has occurred, it will be stored in the getMessage() function of our database connection.

However, if things go well we can start querying the system using the query() function of our $db object. This takes the SQL query to perform as its only parameter, and returns another DB object that contains the result information. To cycle through the result information, a while loop is used, taking advantage of the fetchInto()PEAR::DB function. FetchInto() will return false if it cannot return any more rows, and takes two parameters: where it should send the data it fetches, and how it should store the data there. Using DB_FETCHMODE_ASSOC means that PEAR::DB will set $row up to be an associative array of one row in the result set, recursively iterating through the rows with each while loop.

At the end of the script, the free() and disconnect() functions called. As per usual, this is not required because PHP will clean up connections when scripts are finished, but it is important to make sure you do not give PHP extra work to do. Also as per usual, another good reason to use these two is to free up resources - there is little point hanging on the end of an SQL connection and doing nothing.





<< 9.5 phpMyAdmin   9.6.1 Quick PEAR::DB calls >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 06 Sep 2008

i've installed php normally...
but when i use normal db functions it works but PEAR::DB not working. It is giving blank page..

Any external setting needed for that Plz answer me...
or any configuration for include DB.php!!!!



Send me Reply On::patilsachin4u@rediffmail.com

A PHP User - 06 Sep 2008

If you are getting the "PHP Fatal error: Class 'PEAR_Error' not found" error make sure that you don't have a php script called "pear.php" other than the one in the installation directory.

A PHP User - 06 Sep 2008

Here: http://pear.php.net/package/DB/download
He really should have mentioned that!

fil_mat@dodo.com.au - 06 Sep 2008

I would like to use the flexibilty of DB:PEAR but my php compile complains

PHP Fatal error: Class 'PEAR_Error' not found in /usr/share/pear/DB.php on line 868

Where would I find the PHP class definition for this please?

A PHP User - 06 Sep 2008

becoz he uses "an" instead of "a"

A PHP User - 06 Sep 2008

This author is an real assole!

A PHP User - 06 Sep 2008

I strongle disagree againts "However, if your scripts are only ever going to run locally, there is no real compelling reason to use PEAR::DB. ".

After some practice, one most often comes up with ideas and scripts used elsewhere than locally. By then it is great to know how to use the DB-object. Why not learn PEAR directly instead of the direct functions, as their are equally "hard" to learn?

I see no point in using the direct functions at all. I believe many agree with me. Don't lock yourself in, when it is just as easy to learn the DB-object in the beginning.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is one plus nine?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow