Page 250 - Open Soource Technologies 304.indd
P. 250
Web Technologies-I
Notes 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)
10.4.2 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 placeholders in the
query and sends it to the RDBMS:
$response = $db->execute(compiled, values);
The values 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);
244 LOVELY PROFESSIONAL UNIVERSITY