简体   繁体   中英

Infinite Loop with While inside Foreach and MySQL

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM