看一看这个代码
假设你通过一组在PHP MySQL查询结果的循环
while($temp = mysqli_fetch_assoc($result))
{
echo $temp['id']; // ID Column
}
当你做$ TEMP = mysqli_fetch_assoc($结果),基本上指针移动到下一条记录。 有什么办法来重置指针查询的开始? 由于这种循环mysqli_fetch_assoc($结果)结束后,将只返回空行,会再次转变为不可用。 那么什么是可能的解决办法?
- Quit that thing of printing data directly out of database loop. Learn to separate your business logic from presentation.
- Get yourself a database wrapper, to get rid of all these ugly numerous mysqli_fetch_assoc from your code.
- Store query result in array.
- Use this array as many times as you wish.
Like this
$data = $db->getAll("SELECT * FROM table");
foreach ($data as $row) // 1st iteration
foreach ($data as $row) // 2nd iteration
foreach ($data as $row) // and so on
所以我坚持了今天工作这个问题,我最初发现的唯一的解决办法是重新查询,或在一个变量使用mysql结果的临时副本。 这两者都不是吸引人的。
还有就是这是一个更简单的解决方案,它是mysql_data_seek。
基本语法是mysqli_data_seek(数据,行)
因此,在这种情况下,你只是做
mysqli_data_seek($result,0)
$row=mysqli_fetch_assoc($result);// Will now return the first row.
以类似的方式,你可以遍历它也再次。
它与mysql_data_seek工作方式类似。 希望这是有益的。
文章来源: Mysqli_fetch_assoc($result), pointer moves to the next record. Is there any way to reset the pointer to the start of the query result?