rens
rens

Reputation: 23

Using results of query multiple times

How do I use the result of a query multiple times

$query=...;
$resultsaved=mysql_query($query, $db);
for($i=0;$i<100;$i++){
    $result=$resultsaved;
     while($rowarray = mysql_fetch_array($result, MYSQL_NUM)){
        //do stuff depending on $i and $rowarray
     }
}

However after its first iteration, $resultsaved is destroyed; is there a more efficient way than $result=mysql_query($query, $db); a hundred times

Upvotes: 1

Views: 671

Answers (1)

Sascha Galley
Sascha Galley

Reputation: 16091

You don't need a temporary variable. As the documentation about mysql_fetch_array says:

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

So, after the while loop you need to reset the internal pointer with mysql_data_seek:

$query=...;
$result=mysql_query($query, $db);
for($i=0;$i<100;$i++){
     while($rowarray = mysql_fetch_array($result, MYSQL_NUM)){
        //do stuff depending on $i and $rowarray
     }
     mysql_data_seek($result, 0);
}

Upvotes: 2

Related Questions