Skip to content
Advertisement

How can I loop through a MySQL result set more than once using the mysql_* functions?

For whatever reason, I need to go through a MySQL result set twice. Is there a way to do it?

I don’t want to run the query twice and I don’t want to have to rewrite the script so that it stores the rows somewhere and then reuses them later.

Advertisement

Answer

This is how you can do it:

$result = mysql_query(/* Your query */);
while($row = mysql_fetch_assoc($result)){
 // do whatever here...
}

// set the pointer back to the beginning
mysql_data_seek($result, 0);
while($row = mysql_fetch_assoc($result)){
 // do whatever here...
}

However, I would have to say, this doesn’t seem the right way to handle this. Why not do the processing within the first loop?

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement