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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。