Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 Table ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page