简体   繁体   中英

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.

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.

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):

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. 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'); 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. perhaps what you want is a front-page with a AJAX script that re-checks the database for you in a loop. so that you would have your $.GET, and on the successfull return of your data you'd fire off another $.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
}

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