[英]Infinite Loop with While inside Foreach and MySQL
I'm having a very odd problem with PHP/MySQL... 我在使用PHP / MySQL时遇到一个非常奇怪的问题...
echos "id;id" 回声“ id; id”
foreach($ids as $id) {
echo "id;";
}
echos "id;id;id;id;..." (infinite loop) 回声“ id; id; id; id; ...”(无限循环)
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. 我有一个foreach()语句的原因是因为我对$ ids进行了排序。
You will get an infinite loop, simply because you run the query anew every single time through the while
loop. 您将得到一个无限循环,这仅仅是因为您在while
循环中每次都重新运行查询。 That means, for each $id
, you continuously run the query and extract the first row from it. 这意味着,对于每个$id
,您将连续运行查询并从中提取第一行。 So, for any query that returns more than zero rows, the continual re-execution of that query will make the while
loop endless. 因此,对于返回多于零行的任何查询,该查询的连续重新执行将使while
循环无休止。
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. 这将为每个ID运行一次查询, while
循环将处理该查询的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.