Database Techniques and PHP - Advanced Database Techniques (
Page 4 of 4 )
PEAR DB goes beyond the database primitives shown earlier; it provides several shortcut functions for fetching result rows, as well as a unique row ID system and separate prepare/execute steps that can improve the performance of repeated queries.
Placeholders
Just as printf() builds a string by inserting values into a template, the PEAR DB can build a query by inserting values into a template. Pass the query() function SQL with ? in place of specific values, and add a second parameter consisting of the array of values to insert into the SQL:
$result = $db->query(SQL, values);
For example, this code inserts three entries into the
books
table:
$movies = array(array('Foundation', 1951),
array('Second Foundation', 1953),
array('Foundation and Empire', 1952));
foreach ($books as $book) {
$db->query('INSERT INTO books (title,pub_year) VALUES (?,?)', $book)
;
}
There are three characters that you can use as placeholder values in an SQL query:
|
? |
A string or number, which will be quoted if necessary (recommended) |
|
| |
A string or number, which will never be quoted |
|
& |
A filename, the contents of which will be included in the statement (e.g., for storing an image file in a BLOB field) |
Prepare/Execute
When issuing the same query repeatedly, it can be more efficient to compile the query once and then execute it multiple times using the prepare(), execute(), and executeMultiple() methods.
The first step is to call
prepare()
on the query:
$compiled = $db->prepare(SQL);
This returns a compiled query object. The
execute()
method fills in any placehold
ers in the query and sends it to the RDBMS:
$response = $db->execute(compiled, values);
The
value
s
array contains the values for the placeholders in the query. The return value is either a query response object, or
DB_ERROR
if an error occurred.
For example, we could insert multiple values into the
books
table like this:
$books = array(array('Foundation', 1951),
array('Second Foundation', 1953),
array('Foundation and Empire', 1952));
$compiled = $q->prepare('INSERT INTO books (title,pub_year) VALUES (?,?)');
foreach ($books as $book) {
$db->execute($compiled, $book);
}
The
executeMultiple()
method takes a two-dimensional array of values to insert:
$responses = $db->executeMultiple(compiled, values);
The
values
array must be numerically indexed from 0 and have values that are arrays of values to insert. The compiled query is executed once for every entry in
values
, and the query responses are collected in
$responses
.
A better way to write the book-insertions code is:
$books = array(array('Foundation', 1951),
array('Second Foundation', 1953),
array('Foundation and Empire', 1952));
$compiled = $q->prepare('INSERT INTO books (title,pub_year) VALUES (?,?)');
$db->insertMultiple($compiled, $books);
Please check back next week for the continuation of this article.