如何使用mysql_*函数多次遍历MySQL结果集?

2022-08-30 09:06:34

无论出于何种原因,我都需要对MySQL结果集进行两次检查。有没有办法做到这一点?

我不想运行查询两次,也不想重写脚本,以便它将行存储在某个地方,然后稍后重用它们。


答案 1

这是你如何做到这一点:

$result = mysql_query(/* Your query */);
while($row = mysql_fetch_assoc($result)){
 // do whatever here...
}

// set the pointer back to the beginning
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result)){
 // do whatever here...
}

但是,我不得不说,这似乎不是正确的处理方式。为什么不在第一个循环中进行处理?


答案 2

对于mysqli,您应该执行以下操作;

$result= $con->query($sql); // $con is the connection object
$result->data_seek(0); 

推荐