Consider the following code snippet which has two MySQL queries being fired as part of a loop:
<?php
$requested_names_array = ['ben','john','harry'];
$statement_1 = $connection->prepare("SELECT `account_number` FROM `bank_members` WHERE `name` = :name");
$requested_name = "";
$statement_1->bindParam(":name",$requested_name); //$requested_name will keep changing in value in the loop below
foreach($requested_names_array as $requested_name){
$execution_1 = $statement_1->execute();
if($execution_1){
//fetch and process results of first successful query
$statement_2 = $connection->prepare("SELECT `account_balance` from `account_details` WHERE `account_number` = :fetched_account_number");
$statement_2->bindValue(":fetched_account_number",$fetched_account_number);
$execution_2 = $statement_2->execute();
if($execution_2){
//fetch and process results of second successful query, possibly to run a third query
}
}else{
echo "execution_1 has failed, $statement_2 will never be executed.";
}
}
?>
The problem here is that $statement_2 is prepared time and time again, instead of merely being executed with different parameters.
I don't know if $statement_2 could also be prepared before entering the loop, so it is only executed (and not prepared) as its parameters are changed in the loop, as happens with $statement_1.
In that case, you'd end up with several statements being prepared first, each of them to be executed in the loop that follows.
Even if that would be possible, it might not be efficient, for some statements would be prepared in vain in case the execution of other statements fails.
How would you recommend keeping such a structure optimized?