PHP Application Development With ADODB (part 2) - Rapid Execution (
Page 2 of 7 )
In
the event that you need to execute a particular query multiple times with
different values - for example, a series of INSERT statements - the ADODB class
comes with two methods that can save you a huge amount of time and also reduce
overhead. Consider the following example, which demonstrates:
<?php
// uncomment this to see plaintext output in your browser
// header("Content-Type: text/plain");
// include the ADODB library
include("adodb.inc.php");
// create an object instance
// configure library for a MySQL connection
$db = NewADOConnection("mysql");
// open connection to database
$db->Connect("localhost", "john", "doe", "db278") or die("Unable to
connect!");
// prepare query
$query = $db->Prepare("INSERT INTO library (title, author) VALUES (?,
?)");
// read title-author list in from CSV file
$data = file("list.txt");
// iterate through each line in file
foreach ($data as $l)
{
// split on comma
$arr = explode(",", $l);
// insert values into prepared query
$result = $db->Execute($query, array($arr[0], $arr[1])) or
die("Error in
query: $query. " . $db->ErrorMsg());
}
// clean up
$db->Close;
?>
The Prepare() function, which takes an SQL query as
parameter, readies a query for execution, but does not execute it (kinda like
the priest that walks down the last mile with you to the electric chair).
Instead, prepare() returns a handle to the prepared query, which is stored and
then passed to the Execute() method, which actually executes the query (bzzzt!).
Note the two placeholders used in the query string passed to Prepare() -
these placeholders are replaced by actual values each time Execute() runs on the
prepared statement. The second argument to Execute() is a PHP array containing
the values to be substituted in the query string.
It should be noted that
using Prepare() can provide performance benefits when you have a single query to
be executed a large number of times with different values. However, this benefit
is only available to you if your database system supports prepared queries
(MySQL does not at this time, although Interbase and Oracle do); in all other
cases, only simulated functionality is available and Prepare() becomes
equivalent to a simple Execute(), with no inherent performance
gain.