05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The protocol is the communication protocol to use. The two common values are<br />

"tcp" and "unix", corresponding to Internet and Unix domain sockets. Not every<br />

database backend supports every communications protocol.<br />

These are some sample valid data source names:<br />

mysql:///webdb<br />

mysql://localhost/webdb<br />

mysql://bondview@localhost/webdb<br />

mysql://bondview@tcp+localhost/webdb<br />

mysql://bondview:007@localhost/webdb<br />

In Example 8-1, we connected to the MySQL database webdb with the username<br />

bondview and password 007.<br />

A common development technique is to store the DSN in a <strong>PHP</strong> file and include that<br />

file in every page that requires database connectivity. Doing this means that if the<br />

information changes, you don’t have to change every page. In a more sophisticated<br />

settings file, you might even switch DSNs based on whether the application is running<br />

in development or deployment mode.<br />

Connecting<br />

Once you have a DSN, create a connection to the database using the connect( )<br />

method. This returns a database object you’ll use for tasks such as issuing queries<br />

and quoting parameters:<br />

$db = DB::connect(DSN [, options ]);<br />

The options value can either be Boolean, indicating whether or not the connection is to<br />

be persistent, or an array of options settings. The options values are given in Table 8-2.<br />

Table 8-2. Connection options<br />

Option Controls<br />

persistent Connection persists between accesses<br />

optimize What to optimize for<br />

debug Display debugging information<br />

By default, the connection is not persistent and no debugging information is displayed.<br />

Permitted values for optimize are 'performance' and 'portability'. The<br />

default is 'performance'. Here’s how to enable debugging and optimize for portability:<br />

$db = DB::connect($dsn, array('debug' => 1, 'optimize' => 'portability'));<br />

Error Checking<br />

PEAR DB methods return DB_ERROR if an error occurs. You can check for this with<br />

DB::isError( ):<br />

194 | Chapter 8: Databases<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!