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.

158 ” Database Programming<br />

$author = ’’;<br />

if (ctype_alpha($_GET[’author’]))<br />

{<br />

$author = $_GET[’author’];<br />

}<br />

// Escape the value of $author with quote()<br />

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

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

WHERE author.last_name = ’ . $dbh->quote($author);<br />

// Execute the statement and echo the results<br />

$results = $dbh->query($sql);<br />

foreach ($results as $row)<br />

{<br />

echo "{$row[’title’]}, {$row[’last_name’]}\n";<br />

}<br />

The method PDO::query() returns a PDOStatement object. By default, the fetch<br />

mode for a PDOStatement is PDO::FETCH_BOTH, which means that it will return an<br />

array containing both associative and numeric indexes. It is possible to change the<br />

PDOStatement object to return, for example, an object instead of an array so that<br />

each column in the result set may be accessed as properties of an object instead of<br />

array indices.<br />

$results = $dbh->query($sql);<br />

$results->setFetchMode(PDO::FETCH_OBJ);<br />

foreach ($results as $row)<br />

{<br />

echo "{$row->title}, {$row->last_name}\n";<br />

}<br />

To execute an INSERT, UPDATE, or DELETE statement against a database, PDO provides<br />

the PDO::exec() method. The PDO::exec() method executes an SQL statement and<br />

returns the number of rows affected.<br />

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

$sql = "INSERT INTO book (isbn, title, author_id, publisher_id)<br />

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

$affected = $dbh->exec($sql);<br />

echo "Records affected: {$affected}";

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

Saved successfully!

Ooh no, something went wrong!