PHP Infinite Loop “While” with Class

自古美人都是妖i 提交于 2020-01-07 05:46:10

问题


I made my scripts without class. (framework). Now I have changed my mind & I wanna make my scripts with classes. I like it. But there I have a problem.. Infinite Loop While. I didn't take this problem before with without classes..

While Rule;

while ($fetch=$db->fetchObject($db->q("SELECT * FROM auction_house.items ORDER BY id DESC LIMIT ".$min_stuff.",".$max_stuff."")))
{
    // etc
}

Class;

public function fetchObject($queryRes)
{
    $this->queryRes = $queryRes;
    $this->record = mysql_fetch_object($this->queryRes);
    return $this->record;
}

When I try to while loop, I am taking infinite loop on page. How can I solve this problem?


回答1:


You executing query in each iteration. It always returns a new resource.

Try to separate query and cycle:

$res = $db->q("SELECT * FROM auction_house.items ORDER BY id DESC LIMIT ".$min_stuff.",".$max_stuff."");
while ($fetch=$db->fetchObject($res))
{
    // etc
}



回答2:


Your code is executing on every while loop, so if you keep the $db->q nested there it will execute the query each time it loops, returning for each while iteration the first row of you query result.

try separating your code, like this:

$result = $db->q("SELECT * FROM auction_house.items ORDER BY id DESC LIMIT ".$min_stuff.",".$max_stuff."");
while ($fetch=$db->fetchObject($result)){
    // etc
}

this way the $db->q() will only be executed once, as intended, and the while will loop trough its results.




回答3:


You're starting a new query at each iteration.

You need to store your queryRes:

$queryRes = $db->q("SELECT * FROM auction_house.items ORDER BY id DESC LIMIT ".$min_stuff.",".$max_stuff."");

while ($fetch=$db->fetchObject($queryRes))
{
    // etc
}

On an another side, I'm not sure you should store queryRes and record as instance variable of $db.



来源:https://stackoverflow.com/questions/16417239/php-infinite-loop-while-with-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!