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 thebookstable: $movies = array(array('Foundation', 1951), There are three characters that you can use as placeholder values in an SQL query:
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 callprepare()on the query: $compiled = $db->prepare(SQL); This returns a compiled query object. Theexecute()method fills in any placeholders in the query and sends it to the RDBMS: $response = $db->execute(compiled, values); Thevalues array contains the values for the placeholders in the query. The return value is either a query response object, orDB_ERRORif an error occurred. For example, we could insert multiple values into thebookstable like this: $books = array(array('Foundation', 1951), TheexecuteMultiple()method takes a two-dimensional array of values to insert: $responses = $db->executeMultiple(compiled, values); Thevalues 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 invalues, and the query responses are collected in$responses. A better way to write the book-insertions code is: $books = array(array('Foundation', 1951), Please check back next week for the continuation of this article.
blog comments powered by Disqus |
|
|
|
|
|
|
|