重复mysql结果循环两次

重复mysql结果循环两次

问题描述:

I need to cycle a mysql result twice. so I decided to duplicate its result into a new variable:

$result = mysql_query($query, $db);
$result_copy = $result;

Then I cycle my $result and print the data.
But when I try to cycle $result_copy the while won't work.
I can solve the problem by using mysql_data_seek($result_copy, 0) but I want to understand why the copy won't start from [0].
Thanks in advance!
-----------------------
I'm posting a longer version of my code:

$query = [...];
$result = mysql_query($query, $db);
$result_copy = $result;
while ($row = mysql_fetch_array($result)) {
   [...] // this outputs the data
}
while ($row = mysql_fetch_array($result_copy)) {
    [...] // No data are shown here. Pointer is at the end of $result_copy
}

我需要循环两次mysql结果。 而且我决定将其结果复制到一个新变量中: p>

  $ result = mysql_query($ query,$ db); 
 $ result_copy = $ result; 
  code>  pre> 
 
 

然后 我循环我的 $ result code>并打印数据。
当我尝试循环 $ result_copy code> 时, code>将不起作用。
我可以使用 mysql_data_seek($ result_copy,0) code>解决问题,但我想了解为什么副本不会从[0]开始。
提前谢谢!
-----------------------
我发布了更长版本的代码:
p>

  $ query = [...]; 
 $ result = mysql_query($ query,$ db); 
 $ result_copy = $ result; 
while($ row = mysql_fetch_array($ 结果)){
 [...] //输出数据
} 
而($ row = mysql_fetch_array($ result_copy)){
 [...] //这里没有数据显示。 指针位于$ result_copy 
} 
  code>  pre> 
  div>的末尾

The data rows are retrieved by the mysql_fetch_array($result) statement. If you copy $result you simply are copying the handle (resource id), not the data.

So, you either repeat the while loop, or repeat the action you take wihin the while loop:

<?php

$query = [...];
$result = mysql_query($query, $db);
// $result_copy = $result;

while ($row = mysql_fetch_array($result)) {
   // We got a row here ...
   foreach($row as key => $value) 
       [...] // Do this ...
       [...] // Do that again ...
    }
}

?>

because your $result stored the Resource id

not all the record thats why

I think this is because mysql_query() returns an internal data structure called resource which holds its own pointer to currently processed row. When you do $result_copy = $result; you're not making a copy, you're just assign its pointer to another variable.

Using mysql_data_seek($result, 0) is correct.

The reason is based on the docs of mysql_fetch_array

Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

I suggest that you have to use a clone for create $result_copy. Reason (from PHP5 manual):

As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

So this is reason why is pointer on last position.