PHP Infinite Loop “While” with Class

2019-09-19 06:15发布

问题:

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.