简体   繁体   English

关于循环的while语句的PHP问题

[英]PHP question regarding a while statement for a loop

I asked someone to code up a loop for me, although I asked for the loop to run constantly as it should be doing checks. 我要求有人为我编写一个循环,尽管我要求循环不断运行,因为它应该进行检查。 Say I wanted it to run for 2 hours in a loop. 假设我希望它循环运行2个小时。

They created this; 他们创造了这个;

$result = select_query ('tbltest', 'id,userid,test');

while ($data = mysql_fetch_array ($result))
{
    $userid = $data['userid'];
    $id = $data['id'];
    $test = $data['test'];
}

I don't know much about PHP, but it seems to me that once there are no more rows to go through and place in an array, it will end the loop. 我对PHP不太了解,但是在我看来,一旦没有更多行可以放入数组中,它将结束循环。

How can I go about fetching the rows, but continuing in a loop for the next 2 hours? 我该如何获取行,但是接下来的两个小时要继续循环? Thanks! 谢谢!

I have no idea why you want to continue looping for 2 hours and doing nothing, but here's a solution (albeit a stupid one, if it serves your purpose): 我不知道您为什么要继续循环2小时而什么也不做,但是这是一种解决方案(尽管这很愚蠢,如果它可以满足您的目的):

set_time_limit(0);
$time = time();
while (time()<$time+7200)
{
    if ($data = mysql_fetch_array ($result))
    {
        $userid = $data['userid'];
        $id = $data['id'];
        $test = $data['test'];
    }
    sleep(1); // so PHP doesn't consume too much resources
}

如果要检查一定时间,请设置一个cronjob以每X分钟运行一次PHP脚本,而不要让PHP脚本连续循环。

you can't. 你不能。 when you do the select_query it actually returns a pointer of the full resultset as of that moment. 当您执行select_query时,它实际上返回截至该时刻的完整结果集的指针。 the $data = mysql_fetch_array ($result) can only iterate over that values that were present in the resultset at the time of the initial select_query ('tbltest', 'id,userid,test'); $data = mysql_fetch_array ($result)只能迭代初始select_query ('tbltest', 'id,userid,test');时结果集中存在的值select_query ('tbltest', 'id,userid,test'); call.. not to mention that I can't think of any properly configured PHP server that's going to let you leave a script running for 2 hours without timing out. 呼叫..更不用说我想不出任何配置正确的PHP服务器,它会让您让脚本运行2小时而不会超时。 perhaps what you want is a front-page with a AJAX script that re-checks the database for you in a loop. 也许您想要的是带有AJAX脚本的首页,该脚本可以循环地为您重新检查数据库。 so that you would have your $.GET, and on the successfull return of your data you'd fire off another $.GET... 这样您就可以拥有$ .GET,并在成功返回数据后触发另一个$ .GET ...

Can't you put the original database query inside stillstanding 's loop? 您不能将原始数据库查询放入静止的循环中吗?

set_time_limit(0);
$time = time();
while (time()<$time+7200)
{
    $result = select_query ('tbltest', 'id,userid,test');

    if ($data = mysql_fetch_array ($result))
    {
        $userid = $data['userid'];
        $id = $data['id'];
        $test = $data['test'];
    }
    sleep(1); // so PHP doesn't consume too much resources
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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