0

I ran into a strange problem. I fixed it myself, but I am still curious why it occurs. I thought someone here on StackOverflow might be able to confirm it. I am using something like this in my project :

$users = mysql_query("select * from user where user_id = '$_GET[id]'") or die("Connection Error");
while($user = mysql_fetch_array($users))
$user_activated = $user['user_activated'];

// For testing purpose. This is not my original code but it's in the same sequence.
while($user = mysql_fetch_array($users))
echo "Test".

The echo "Test" never happens. Should there be any change happening to the $users array? Or is it automatically erased? I never came across anything quite like it. Can anyone provide some intuition into this?

Thank you!

4

3 回答 3

1

当您获取行时,有一个内部指针可以跟踪您在资源中的位置。一旦你完成了,你必须使用mysql_data_seek()回到开始并能够再次查看获取。

但是,如果您需要再次提取数据,最好的办法是第一次将其存储在数组中,如下所示:

while($user = mysql_fetch_array($users)) {
    $users_array[] = $user;
}

然后,您可以查看$users所有您想要的数组,而无需从资源中重新获取。

附带说明一下,您也应该切换到 PDO。除了不被弃用之外,您还可以访问该fetchAll()方法。

于 2013-07-30T14:06:48.277 回答
1

一旦你使用了一个结果集,mysql_指针就位于记录集的末尾。当您要求迭代器再次使用它时,因为该点位于结果的末尾,因此不会发生迭代。在结果集的开头重置指针使用

mysql_data_seek($rs, 0);
于 2013-07-30T14:07:46.720 回答
1

记录没有被删除,但 mysql_fetch_array 使用指针并对其进行迭代,您可以使用 mysql_data_seek 将指针重置为初始结果,如下所示:

$users = mysql_query("select * from user where user_id = '$_GET[id]'") or die("Connection Error");
while($user = mysql_fetch_array($users))
$user_activated = $user['user_activated'];
// reset the pointer
mysql_data_seek($users,0) 

// For testing purpose. This is not my original code but it's in the same sequence.
while($user = mysql_fetch_array($users))
echo "Test".
于 2013-07-30T14:18:16.517 回答