Loop mysql result set multiple times or twice in php

First we will select something from the database and loop through it like so:

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

Problem:

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.

Solution:

we need to put the pointer back at the beginning of the result set so that it can loop again.

For mysql,

[php]
mysql_data_seek($result, 0);
[/php]

For mysqli,

[php]
mysqli_data_seek($result, 0);
[/php]

Now we got solution for this problem.
[php]
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
}
[/php]

Permanent link to this article: https://blog.openshell.in/2013/01/loop-mysql-result-set-multiple-times-or-twice-in-php/

Leave a Reply

Your email address will not be published.