将具有相同结果集的mysql_fetch_array放在两个循环中不起作用


putting mysql_fetch_array with the same result set within two loops doesn't work

第一个循环做得很好,但第二个循环做得不好。例如:

$sql = "select * from table";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
  //some code
}
while($row=mysql_fetch_array($result))
{
  //some code
}

我只想知道为什么

在我回答后,我做了更多的研究,并在下面的编辑中发布了正确的版本

因为这是数组迭代器在 PHP 中的工作方式,所以重置指针应该可以解决问题:

while($row=mysql_fetch_array($result))
{
  //some code
}
// reset($result); - won't work with mysql_query() result
mysql_data_seek($result, 0);
while($row=mysql_fetch_array($result))
{
   //some code
}

在此处阅读有关 reset() 函数的更多信息

编辑:经过更多的研究,我发现我错了 - 使用mysql_data_seek

mysql_data_seek($result, 0);

一旦你通过第一个while循环获取结果集的所有数据,那么指针就会转到最后一条记录,因此它不会在第二个while循环中获取任何内容。您需要将指针设置回第一条记录,然后再将其再次传递给 while 循环。

只需像这样更新您的代码:

$sql = "select * from table";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
  //some code
}
mysql_data_seek(0); // Add this line
while($row=mysql_fetch_array($result))
{
  //some code
}
你可以

像这样复制$result

$sql = "select * from table";
$result=mysql_query($sql);
$result2 = $result;
while($row=mysql_fetch_array($result))
{
  //some code
}
while($row=mysql_fetch_array($result2))
{
  //some code
}