05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

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

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

Placeholders<br />

Just as printf( ) builds a string by inserting values into a template, the PEAR DB can<br />

build a query by inserting values into a template. Pass the query( ) function SQL with<br />

? in place of specific values, and add a second parameter consisting of the array of<br />

values to insert into the SQL:<br />

$result = $db->query(SQL, values);<br />

For example, this code inserts three entries into the movies table:<br />

$movies = array(array('Dr No', 1962),<br />

array('Goldfinger', 1965),<br />

array('Thunderball', 1965));<br />

foreach ($movies as $movie) {<br />

$db->query('INSERT INTO movies (title,year) VALUES (?,?)', $movie);<br />

}<br />

There are three characters that you can use as placeholder values in an SQL query:<br />

? A string or number, which will be quoted if necessary (recommended)<br />

| A string or number, which will never be quoted<br />

& A filename, the contents of which will be included in the statement (e.g., for<br />

storing an image file in a BLOB field)<br />

Prepare/Execute<br />

When issuing the same query repeatedly, it can be more efficient to compile the<br />

query once and then execute it multiple times, using the prepare( ), execute( ), and<br />

executeMultiple( ) methods.<br />

The first step is to call prepare( ) on the query:<br />

$compiled = $db->prepare(SQL);<br />

This returns a compiled query object. The execute( ) method fills in any placeholders<br />

in the query and sends it to the RDBMS:<br />

$response = $db->execute(compiled, values);<br />

The values array contains the values for the placeholders in the query. The return<br />

value is either a query response object, or DB_ERROR if an error occurred.<br />

For example, we could insert multiple values into the movies table like this:<br />

$movies = array(array('Dr No', 1962),<br />

array('Goldfinger', 1965),<br />

array('Thunderball', 1965));<br />

$compiled = $q->prepare('INSERT INTO movies (title,year) VALUES (?,?)');<br />

foreach ($movies as $movie) {<br />

$db->execute($compiled, $movie);<br />

}<br />

198 | Chapter 8: Databases<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!