25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

156 ” Database Programming<br />

<strong>PHP</strong> Data Objects (PDO)<br />

The standard distribution of <strong>PHP</strong> 5.1 and greater includes PDO and the drivers for<br />

SQLite by default. However, there are many other database drivers for PDO, including<br />

Microsoft SQL Server, Firebird, MySQL, Oracle, PostgreSQL, and ODBC. Refer to<br />

the PDO documentation on the <strong>PHP</strong> Web site for details on how to install each of<br />

these drivers. Once installed, the process for using each driver is, for the most part,<br />

the same because PDO provides a unified data access layer to each of these database<br />

engines. There is no longer a need for separate mysql_query() or pg_query() functions.<br />

PDO provides a single object-oriented interface to these databases.<br />

The difference comes in the SQL used for each database since each database engine<br />

provides its own specialized keywords. PDO does not provide a means for standardizing<br />

statements across database engines. Thus, when switching an application<br />

from one database to another, you will need to pay careful attention to the SQL statements<br />

issued from your application to ensure that they do not contain keywords and<br />

functionality that the new database engine does not recognize.<br />

Connecting To a Database With PDO<br />

To connect to a database, PDO requires at least a Data Source Name, or DSN, formatted<br />

according to the driver used. Detailed DSN formatting documentation exists on<br />

the <strong>PHP</strong> Web site for each driver. Additionally, if your database requires a username<br />

or password, PDO will need these to access the database. A sample connection to a<br />

MySQL database using the library database described earlier might look like this:<br />

$dsn = ’mysql:host=localhost;dbname=library’;<br />

$dbh = new PDO($dsn, ’dbuser’, ’dbpass’);<br />

Since each of these examples assumes a MySQL database, it’s worth mentioning here<br />

that the MySQL client library contains a few quirks that cause some irregularities<br />

when using the PDO_MYSQL driver, specifically with regard to prepared statements.<br />

To solve these irregularities it is necessary to set a PDO attribute after connecting<br />

to the database. The following line of code will set PDO to use its own native query<br />

parser for prepared statements instead of the MySQL client library API.<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)

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

Saved successfully!

Ooh no, something went wrong!