Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy sql result from one variable to other

Tags:

php

How to copy sql result from one variable to other without arrays and foreach in PHP.

$query="Select * from table";
$res1=mysql_query($query);
$res2=$res1; // I need somethink like this, simply, like in other languages
while($row=mysql_fetch_array($res1)) {
echo $row['Id'];
}
echo '<br>';
while($row=mysql_fetch_array($res2)) {
echo $row['Id'];
}

First while will print id, second not print.

like image 409
Michael Avatar asked Jan 07 '23 17:01

Michael


1 Answers

For SELECT queries mysql_query() returns a resource on success, which is a special variable holding a reference to the result set. In this statement $res2=$res1; you're only copying the reference to another variable, not the actual result set. And in the first while loop you have already iterated the result set, hence assigning the resource to another variable won't reset it back.

But you can use mysql_data_seek() function to adjust the result pointer to point to the beginning of the result set so that you could iterate through it again.

Here's the reference:

  • mysql_data_seek()

So your code should be like this:

$query="Select * from table";
$res=mysql_query($query);

while($row=mysql_fetch_array($res)) {
    echo $row['Id'];
}
echo '<br />';

mysql_data_seek($res, 0);

while($row=mysql_fetch_array($res)) {
    echo $row['Id'];
}

Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.

like image 88
Rajdeep Paul Avatar answered Jan 15 '23 16:01

Rajdeep Paul