PDO also allows for what is known as prepared statements. This is done with PDO calls in stages or steps. Consider the following code:
$stmt = $ConnHandle->prepare( "SELECT * FROM books"); $stmt->execute();
while ($row = $stmt->fetch()) { // gets rows one at a time print_r ($row); // or do something more meaningful with each returned row } $stmt = null;
In this code, we “prepare” the SQL code then “execute” it. Next, we cycle through the result with thewhilecode and, finally, we release the result object by assigningnullto it. This may not look all that powerful in this simple example, but there are other features that can be used with prepared statements. Now, consider this code:
Here, we prepare the SQL statement with four named placeholders:authorid, title,ISBN, andpub_year. These happen to be the same names as the columns in the database. This is done only for clarity; the placeholder names can be anything that is meaningful to you. In the execute call, we replace these placeholders with the actual data that we want to use in this particular query. One of the advantages of prepared statements is that you can execute the same SQL command and pass in different values through the array each time. You can also do this type of statement preparation with positional placeholders (not actually naming them), signified by a?, which is the positional item to be replaced. Look at the following variation of the previous the code:
This code accomplishes the same thing but with less code, as the value area of the SQL statement does not name the elements to be replaced, and, therefore, the array in the execute statement only needs to send in the raw data and no names. You just have to be sure about the position of the data that you are sending into the prepared statement.
This was just a brief overview of what the new PDO library will be able to do for you in the database realm of PHP. If you want to explore this new library in more depth, be sure to do your research and testing before using it in a production environment. You can find information on PDO at http://ca.php.net/pdo.