If you have a complex query you can write this way for the easier readability:
$query1 = 'select Name from Customers where CustId = :custid';
$query2 = 'select Name from Sales where SalesId = :salesid';
$sth1 = $dbh->prepare($query1);
$sth2 = $dbh->prepare($query2);
if ($x > 10) {
$sth1->bind_param('custid', $custid);
$sth1->execute();
while ($row = $sth1->fetchrow_hashref) {
...
}
} else {
$sth2->bind_param('salesid', $salesid);
$sth2->execute();
while ($row = $sth2->fetchrow_hashref) {
...
}
}
'prepare' can be replaced with 'prepare_cached' in order to avoid multiple preparation.
Excerpt from DBI man page:
Like "prepare" except that the statement handle returned will be store
+d in a hash associated with the $dbh. If another call is made to "pre
+pare_cached" with the same $statement and %attr parameter values, the
+n the corresponding cached $sth will be returned without contacting t
+he database server.
Update:
I am not sure that this kind of named binding work with MySQL.
|