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.

164 ” Database Programming<br />

Since mysqli provides the mysqli class through its object-oriented interface, it is<br />

possible to extend this class, if desired, and cause it to throw exceptions on errors, as<br />

well as provide other functionality to the child class.<br />

For all other examples in this section, replace the // All other database calls go<br />

here message with the example code.<br />

Querying the Database With mysqli<br />

To retrieve a result set from a database using mysqli, you may use the<br />

mysqli::real_query() (for the OOP approach) or mysql_real_query() (procedural)<br />

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

etc.) use the mysqli::real_escape_string() or mysqli_real_escape_string() methods.<br />

Using these escape methods, mysqli will ensure that the string is quoted<br />

properly for the database, taking into account the current character set for the<br />

database. See the Security chapter for more discussion on escaping strings for<br />

database queries.<br />

The mysqli extension also provides the simpler mysqli::query() and<br />

mysqli_query() methods, which will immediately return a result set. With<br />

mysqli::real_query() or mysqli_real_query() the result set is not returned until<br />

mysqli::store_result(), mysql_store_result(), mysqli::use_result(), or<br />

mysql_use_result() are called. Using the * real_query methods is beneficial, however,<br />

since these methods allow you to call stored procedures and work with buffered<br />

queries. The following examples for querying the database use the * real_query<br />

methods.<br />

// Filter input from $_GET<br />

$author = ’’;<br />

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

{<br />

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

}<br />

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

// Escape the value of $author with mysqli->real_escape_string()<br />

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

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

WHERE author.last_name = ’ . $mysqli->real_escape_string($author);<br />

// Execute the statement and echo the results

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

Saved successfully!

Ooh no, something went wrong!