Looping Through MySQL Result Sets Multiple Times with mysql_* Functions
It may occasionally be necessary to iterate through a MySQL result set more than once. Despite its simplicity, this task presents some challenges. One would ideally prefer to avoid re-running the query or manually storing the rows for reuse.
Solution:
The mysql_* functions provide a straightforward solution:
$result = mysql_query(/* Your query */); while ($row = mysql_fetch_assoc($result)) { // Perform operations on the row } // Reset the result pointer to the beginning mysql_data_seek($result, 0); while ($row = mysql_fetch_assoc($result)) { // Perform operations on the row }
This approach allows you to iterate through the result set twice or more without incurring the overhead of re-executing the query.
However, it's worth considering why you might need to loop through the result set multiple times. In many cases, it may be more efficient to perform all necessary operations within the first loop itself.
The above is the detailed content of How to Iterate Through a MySQL Result Set Multiple Times Using mysql_* Functions?. For more information, please follow other related articles on the PHP Chinese website!