0

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?

1 Answer 1

2

You should re-write as a join:

SELECT account_number, account_balance
FROM bank_members
INNER JOIN account_details ON bank_members.account_number = account_details.account_number

one single query, prepared once, executed once, fetching all the data you need.

Sign up to request clarification or add additional context in comments.

3 Comments

Just a side note: INNER JOIN is the same as JOIN
@PiontekMedia: I tend to always explicitly specify the join type. later in the day I might not be as conscious.
Haha fair enough, just thought I'd point it out. Really just personal preference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.