Loop twice through a PHP / MYSQL result set

I get asked all the time if it is possible to loop multiple times through a MySQL result set in PHP. Here’s the answer.

First, you’ll need a MySQL result set. To do that you’ll need to select something from your database and loop through it like so:

$result = mysql_query("SELECT * FROM my_table");
while($row = mysql_fetch_assoc($result)) {
// inside the loop

The problem is, if you want to loop through the same result set again, you will get an error because the internal pointer is currently at the end of the result. You will need to put the pointer back at the beginning of the result set so that you can loop through it again.

You can do it with a helpful php function named mysql_data_seek.

mysql_data_seek($result, 0); // set the pointer of the result set back to the beginning.
while($row2 = mysql_fetch_assoc($result)) {
// inside the loop 

This demonstrates how, as a PHP website developer, you can reset the pointer of a MySQL result set, which will allow you to iterate through the result set for a second time.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s