why does mysqli fetch create an infinite loop when in function?

寵の児 提交于 2020-01-05 07:29:28

问题


Why does this function return an infinite loop? I am trying to create a function where you just have to give it the query and the while loop takes care of the rest. but for some reason ONLY when i have the function return $q->fetch_assoc() it goes into an infinite loop. if I return just $q, then call $q->fetch_assoc() in the while loop then it doesn't cause the infinite loop.

public function fetch($query){
    $con = $this->con;
    $q = $con->query($query);

    return $q->fetch_assoc();
}

while($r = $sqli->fetch("SELECT id FROM users LIMIT 5")){
    echo $r['id']."<br />";
}

also tried

public function fetch($query){
    $con = $this->con;
    $q = $con->query($query);

    return $q->fetch_assoc();
}

$x = $sqli->fetch("SELECT id FROM users LIMIT 5");

while($r = $x){
    echo $r['id']."<br />";
}

I thought maybe it was recreating a new fetch function every time. This too did not work and caused the infinite loop.


回答1:


Every time you call the function you RE-RUN the query, which resets the data set to the first record.

e.g. You have 5 records that get returned:

function get() {
    .... run query
    return 1st record
}

You'll NEVER get records 2,3,4,5 because you keep resetting the query to the beginning.

Your function should be returning the result HANDLE:

function do_query($sql) {
    $result = $con->query($sql);
    return $result;
}

while($row = $result->fetchRow()) {
   ...
}



回答2:


fetch function has problem , when call this function reset query(reinitialize query) and fetching only first row without to indicate to next row.you have two way first way is use query function then use fetch function in while-loop.

public function query($sql){
    $con = $this->con;
    return $con->query($sql); // as result


}
public function fetch($result){

    return $result->fetch_assoc();
}
$query_r=this->query("SELECT id FROM users LIMIT 5"); // as result
while($r = $this->fetch($query_r)){
    echo $r['id']."<br />";
}

second way is smarter,use key/value query cache for save query(avoid reset/reinitliazing queries) and this way closer to your prototype

public $query_cache=array();
private function query($sql){
    $con = $this->con;
    return $con->query($sql); // as result


}
public function fetch($sql){
    $cache_item=@$this->query_cache[$sql];
    if(!$cache_item) { $cache_item=$this->query($sql);$this->query_cache[$sql]=$cache_item; }
    $row=$cache_item->fetch_assoc();
    if(!$row) unset($this->query_cache[$sql]);
    return $row;
}

while($r = $this->fetch("SELECT id FROM users LIMIT 5")){
    echo $r['id']."<br />";
}


来源:https://stackoverflow.com/questions/26019237/why-does-mysqli-fetch-create-an-infinite-loop-when-in-function

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