duanjiaopi8218 2014-09-24 14:16
浏览 49
已采纳

为什么mysqli fetch在函数中创建一个无限循环?

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.

  • 写回答

2条回答 默认 最新

  • doufeixuan8882 2014-09-24 14:28
    关注

    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()) {
       ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件