Note that there are some explanatory texts on larger screens.

plurals
  1. POOptimizing multiple MySQL queries in a loop with PDO
    primarykey
    data
    text
    <p>Consider the following code snippet which has two MySQL queries being fired as part of a loop:</p> <pre><code>&lt;?php $requested_names_array = ['ben','john','harry']; $statement_1 = $connection-&gt;prepare("SELECT `account_number` FROM `bank_members` WHERE `name` = :name"); $requested_name = ""; $statement_1-&gt;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-&gt;execute(); if($execution_1){ //fetch and process results of first successful query $statement_2 = $connection-&gt;prepare("SELECT `account_balance` from `account_details` WHERE `account_number` = :fetched_account_number"); $statement_2-&gt;bindValue(":fetched_account_number",$fetched_account_number); $execution_2 = $statement_2-&gt;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."; } } ?&gt; </code></pre> <p>The problem here is that <strong>$statement_2 is prepared time and time again</strong>, instead of merely being executed with different parameters.</p> <p>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.</p> <p>In that case, you'd end up with several statements being prepared first, each of them to be executed in the loop that follows.</p> <p>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.</p> <p>How would you recommend keeping such a structure optimized?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload