ループの一部として2つのMySQLクエリが実行される次のコードスニペットについて考えてみます。
<?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.";
}
}
?>
ここでの問題は、$ statement_2が単に異なるパラメーターで実行されるのではなく、何度も準備されることです。
$ statement_2もループに入る前に準備できるかどうかわからないので、$ statement_1の場合と同様に、パラメーターがループ内で変更されたときにのみ実行されます(準備されません)。
その場合、最初にいくつかのステートメントが準備され、それぞれが次のループで実行されることになります。
それが可能であったとしても、他のステートメントの実行が失敗した場合に備えて、一部のステートメントが無駄に準備されるため、効率的ではない可能性があります。
このような構造を最適化しておくことをどのように推奨しますか?