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.

Database Programming ” 157<br />

For the remainder of this chapter, you’ll notice the use of try/catch statements<br />

(described in Chapter 6, OOP Programming). This is not only a best practice,<br />

but it is very useful in debugging. Note that the default error mode for PDO<br />

is PDO::ERRMODE_SILENT, which means that it will not emit any warnings or error<br />

messages. For the examples in this chapter, however, the error mode is set to<br />

PDO::ERRMODE_EXECEPTION. This causes PDO to throw a PDOExecption when an error<br />

occurs. This exception can be caught and displayed for debugging purposes. The<br />

following illustrates this setup; assume that all code examples replace the comment.<br />

try<br />

{<br />

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

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

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);<br />

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);<br />

// All other database calls go here<br />

}<br />

catch (PDOException $e)<br />

{<br />

echo ’Failed: ’ . $e->getMessage();<br />

}<br />

Querying the Database With PDO<br />

To retrieve a result set from a database using PDO, use the PDO::query() method.<br />

To escape a value included in a query (e.g. from $_GET, $_POST, $_COOKIE, etc.) use<br />

the PDO::quote() method. PDO will ensure that the string is quoted properly for the<br />

database used.<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

i<br />

Not all database drivers for PDO implement the PDO::quote() method. For this reason,<br />

and for the best possible approach to security, it is best to use prepared statements<br />

and bound parameters, described in the next section.<br />

// Filter input from $_GET

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

Saved successfully!

Ooh no, something went wrong!