prepareQuery() and executeQuery*() give you more power and flexibilty for query execution. You can use them, if you have to do more than one equal query (i.e. adding a list of adresses to a database) or if you want to support different databases, which have different implementations of the SQL standard.
Imagine you want to support two databases with different INSERT syntax:
<?php
$statement['db1']['INSERT_PERSON'] = "INSERT INTO person ( surname, name, age ) VALUES ( ?, ?, ? )" ;
$statement['db2']['INSERT_PERSON'] = "INSERT INTO person SET surname=?, name=?, age=?" ;
?>
To use the features above, you have to do two steps. Step one is to prepareQuery the statement and the second is to executeQuery it.
Prepare() has to be called with the generic statement at least once. It returns a handle for the statement.
To create a generic statement is simple. Write the SQL query as usual, i.e.
prepareQuery() can handle different types of placeholders or wildcards.
After preparing the statement, you can execute the query. This means to assign the variables to the prepared statement. To do this, executeQuery() requires two arguments, the statement handle of prepareQuery() and an array with the values to assign. The array has to be numerically ordered. The first entry of the array represents the first wildcard, the second the second wildcard etc. The order is independent from the used wildcard char.
Inserting data into a datebase
<?php
$alldata = array( array(1, 'one', 'en'),
array(2, 'two', 'to'),
array(3, 'three', 'tre'),
array(4, 'four', 'fire'));
$sth = $dbh->prepareQuery("INSERT INTO numbers VALUES(?,?,?)");
foreach ($alldata as $row) {
$dbh->executeQuery($sth, $row);
}
?>
In the example the query is done four times:
Using executeMultiple() instead of executeQuery()
<?php
...
$alldata = array( array(1, 'one', 'en'),
array(2, 'two', 'to'),
array(3, 'three', 'tre'),
array(4, 'four', 'fire'));
$sth = $dbh->prepareQuery("INSERT INTO numbers VALUES(?,?,?)");
$dbh->executeMultiple($sth, $alldata);
}
?>
The result is the same. If one of the records failed, the unfinished records will not be executed.
If executeQuery*() fails a MDB_Error, else MDB_OK will returned.