Ryan Butterworth Ryan Butterworth - 5 months ago 41
SQL Question

PHP/MySQL: simultaneous queries inside WHILE loop?

I'm trying to execute a query inside a WHILE loop running on

mysqli_fetch_array
. The query gives the following error:

Error: Commands out of sync; you can't run this command now


I found out that you can't have simultaneous queries. Here's my code

$query "SELECT * FROM table";
$exec = mysqli_query($con, $query);

while($loop = mysqli_fetch_array($exec)){

$data = $loop['data'];

$sim = "SELECT * FROM table2 WHERE col1 = '$data'";
$execsim = mysqli_query($con, $sim);
$getsim = mysqli_fetch_array($execsim);
$somedata = $getsim['somedata'];

//insert $somedata and $data into table3

}


After some research, I see that
store_result()
could be useful here. Excuse my ignorance as this is new to me. There aren't any examples/solutions that I can find that use this with a WHILE loop scenario (does that make a difference?) - most are in object oriented style too.

What is the most effective way around this problem?

Answer

The most effective workaround for this is to avoid processing row-by-agonizing-row (RBAR), and just perform the operation on the set, and be done with it.

INSERT INTO table3 (somedata, col1)
SELECT t2.somedata
     , t2.col1
  FROM table2 t2
  JOIN table1 t1
    ON t1.data = t2.col1
 ORDER BY t2.somedata, t2.col1

If this doesn't satisfy the requirements, then some requirements have been omitted from the specification, and we can only guess what you are actually trying to achieve.

As another option, avoid the two queries, and just use a join operation, as shown in the INSERT ... SELECT statement above. (Just start with the SELECT).

No indication given in the specification as to the reason for an excruciating loop within a loop, to process rows individually.