0

I'm having a very odd problem with PHP/MySQL...

echos "id;id"

 foreach($ids as $id) {
      echo "id;";
 }

echos "id;id;id;id;..." (infinite loop)

 foreach($ids as $id) {
      while($row = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM `Table` WHERE `id`=$id;") {
           echo "id;";
      }
 }

The reason I have a foreach() statement is because I have $ids sorted.

1 Answer 1

1

You will get an infinite loop, simply because you run the query anew every single time through the while loop. That means, for each $id, you continuously run the query and extract the first row from it. So, for any query that returns more than zero rows, the continual re-execution of that query will make the while loop endless.

It's functionally similar in effect to the following pseudo-code, which will also loop forever since you're modifying the control condition within the loop:

loop i from 1 to 10
    set i to 1
endloop

You should instead try something like:

foreach($ids as $id) {
    $result = mysqli_query($conn, "SELECT * FROM `Table` WHERE `id`=$id;");
    while($row = mysqli_fetch_array($result)) {
       echo "id;";
    }
}

This will run the query once for each ID and the while loop will process the rows for that query.

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

3 Comments

There's only two values in $ids, so why is it running the query more than twice?
@rtainc, the infinite loop is the while, not the foreach. I'll clarify.
@rtainc, relax, I've done far sillier things in my long career, none of which I'll admit to here :-)

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.