CHAPTER 6 – PEAR DB – Database Connections

PEAR DB borrows the term data source name (DSN) from ODBC to describe how a database is addressed.

 Data Source Names DSNs use the uniform resource identificator (URI) format. This is an example DSN that refers to a mysql database on local- host called "world": mysql://user:password@host/world The full DSN format is a lot more verbose than this, and most fields are optional. In fact, only the database extension name is mandatory for all drivers. The database extension determines which DB driver is used, and which other DSN fields are required depends on the driver. These are some example DSNs: dbext dbext://host dbext://host/database dbext://user:pw@host/database dbext://user:pw@host dbext(dbtype)://user:pw@protocol+host:port//db/file.db?mode=x dbext is the database back-end driver. The drivers bundled with DB are dbase, fbsql, ibase, ifx, msql, mssql, mysql, mysqli, oci8, odbc, pgsql, sqlite, and sybase. It is possible to install additional drivers as separate packages. The syntax of the DSN URI is the same for all drivers, but which fields are required varies depending on the back-end database's features. This section uses mysql for examples. Consult the PEAR DB online manual for DSN details.

Establishing Connections Here is an example of how to establish a database connection using PEAR DB: <?php require_once 'DB.php'; $dbh = DB::connect("mysql://test@localhost/test"); if (DB::isError($dbh)) { print "Connect failed!n"; print "Error message: " . $dbh->getMessage() . "n"; print "Error details: " . $dbh->getUserInfo() . "n"; exit(1); } print "Connect ok!n"; This script connects to the "test" database using the mysql extension. The database server runs on localhost, and the connection will be opened as user "test" with no password. DB.php is the only file you need to include to use PEAR DB. DB::connect() is a factory method that includes the right file for your driver. It creates a driver object, initializes it, and calls the native function for creating the actual connec- tion. DB::connect() will raise a PEAR error on failure. For SQLite databases, all you need to specify is the PHP extension and the database file, like this: sqlite:///test.db Here, "test.db" will be opened from the current directory. To specify the full path, the database file name must be prefixed with yet another slash, like this: sqlite:////var/lib/sqlite/test.db

Post Comment
Login to post comments