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
}
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.