Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 限制while循环_Php_Mysql_While Loop - Fatal编程技术网

Php 限制while循环

Php 限制while循环,php,mysql,while-loop,Php,Mysql,While Loop,从mysql获取数据时,有没有办法限制while循环 $query = "SELECT * FROM `table` WHERE user_id = '$id' ORDER BY `ID` DESC"; $result = mysql_query($query); while ($info = mysql_fetch_assoc($result)) { //stuff } 这里我不想使用mysql的LIMIT函数,我可以限制while循环而不是那个循

从mysql获取数据时,有没有办法限制while循环

$query = "SELECT * 
    FROM  `table` 
    WHERE user_id = '$id' 
    ORDER BY `ID` DESC";

$result = mysql_query($query);

while ($info = mysql_fetch_assoc($result)) {
    //stuff
}
这里我不想使用mysql的LIMIT函数,我可以限制while循环而不是那个循环吗


谢谢

当循环达到目标时,您总是可以
打破它。否则,您可以按照Nick的建议使用
for
循环

$count = 0;

while ($count < 4 && $info = mysql_fetch_assoc($result)) {
    //stuff

    $count++;
}
$count=0;
而($count<4&&$info=mysql\u fetch\u assoc($result)){
//东西
$count++;
}

但是请注意,最好使用
limit
命令限制查询结果集。

只需添加行数检查:

while ($rowcount < 100 && $info = mysql_fetch_assoc($result)) {
    $rowcount += 1;
//stuff
}
while($rowcount<100&&$info=mysql\u fetch\u assoc($result)){
$rowcount+=1;
//东西
}

使用
循环。例如,要循环最多五行

for ($i = 0; $info = mysql_fetch_assoc($result) && $i < 5; ++$i) {
    // do stuff
}
for($i=0;$info=mysql\u fetch\u assoc($result)&&$i<5;++$i){
//做事
}

您可以提前跳出PHP循环-但是您应该使用mysql LIMIT子句-当您调用mysql_query()时,整个结果集从数据库中获取并传输到客户端,这可能会造成内存和性能问题。

您可以使用
break
结束循环

所以,它可能是

$result = mysql_query($query);
$count=0;

while ($info = mysql_fetch_assoc($result)) {

if($info=="what you're looking for"){ $count+=1; }

if($count >= 4){ break; }//break will exit the while loop
}

php文档

那么我如何知道它是否获取了示例4记录?用一个示例更新了答案。但是请注意,限制SQL查询中的循环可能是一个更好的主意。我有一些无法用mysql查询筛选的数据,我需要检查所有字段,这就是为什么我要在while循环中筛选它们,所以我需要限制while循环