25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

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

Database Programming ” 161<br />

The following illustrates the use of question mark placeholders instead of named<br />

placeholders.<br />

$sql = ’SELECT author.*, book.* FROM author<br />

LEFT JOIN book ON author.id = book.author_id<br />

WHERE author.last_name = ?’;<br />

$stmt = $dbh->prepare($sql);<br />

$stmt->bindParam(1, $author1, PDO::PARAM_STR, 20);<br />

Prepared statements with bound parameters are perhaps among the most useful and<br />

powerful features of PDO.<br />

Transactions With PDO<br />

For databases that natively support transactions, PDO implements transaction functionality<br />

with the PDO::beginTransaction(), PDO::commit(), and PDO::rollBack()<br />

methods. PDO does not try to emulate transactions for those database engines that<br />

do not support them. See the Transactions section earlier in this chapter for more<br />

information on how transactions work.<br />

The following code again shows the full example including the try/catch statements.<br />

If any of the statements executed against the database fail, then PDO<br />

will throw an exeception. When catch catches the the exeception, you can call<br />

PDO::rollBack() to ensure that any actions taken during the transaction are rolled<br />

back. Here, one of the INSERT statements fails to list all columns for which it has values.<br />

Thus, it throws an exeception and the valid INSERT statement executed earlier is<br />

not committed to the database.<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 />

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

$dbh->beginTransaction();<br />

$dbh->exec("INSERT INTO book (isbn, title, author_id, publisher_id)<br />

VALUES (’0395974682’, ’The Lord of the Rings’, 1, 3)");<br />

$dbh->exec("INSERT INTO book (title) VALUES (’Animal Farm’, 3, 2)");

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

Saved successfully!

Ooh no, something went wrong!