PEAR::DB

PEAR::DB is an advanced, object-oriented database library that provides full database abstraction—that is, you use the same code for 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 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 with SQL syntax, such as the LIMIT clause. In PHP 5.1, there's a new extension called PHP Data Objects (PDO) that abstracts only the functions, which is halfway between PEAR::DB and using normal DB calls. PEAR::DB is likely to be updated to use PDO, as it's much more efficient.

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

    include_once('DB.php');

    $conninfo = "mysql://username:password@localhost/phpdb";
    $db = DB::connect($conninfo);

    if (DB::isError($db)) {
            print $db->getMessage();
            exit;
    }

    $result = $db->query("SELECT * FROM people;");

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

    $result->free();
    $db->disconnect();

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

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.