为什么mysqli fetch在函数中创建一个无限循环? [英] why does mysqli fetch create an infinite loop when in function?
问题描述
为什么这个函数返回一个无限循环?我试图创建一个函数,你只需要给它查询和while循环负责其余的。但由于某种原因,只有当我有函数返回$ q-> fetch_assoc()它会进入无限循环。如果我只返回$ q,然后在while循环中调用$ q-> fetch_assoc(),那么它不会导致无限循环。
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 />;
}
也曾尝试过
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 />;
}
我想也许是每次重新创建一个新的获取函数。这也不起作用,并导致了无限循环。
每次调用函数时,都会重新运行查询,将数据集重置为第一条记录。
例如你有5条记录被返回:
function get(){
.... run query
返回第一条记录
}
您将永远获得记录2,3,4,5,因为你不断重置查询到开始。
你的函数应该返回结果HANDLE:
函数do_query($ sql){
$ result = $ con> query($ sql);
返回$ result;
}
while($ row = $ result-> fetchRow()){
...
}
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.
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()) {
...
}
这篇关于为什么mysqli fetch在函数中创建一个无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!