Apr

20

If you use PHP to query MySQL database once, output the array of data and later want to retrieve the result again. One example is when you want to retrieve the list of array results ordered randomly and later when you retrieve the same list of results, you want it to be the same random list order. Like the one below, you will find that it won’t just work out of the box.

$sql = "SELECT * from table ORDER BY RAND()";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
// do stuff with $row
}

while ($row = mysql_fetch_assoc($result)) {
// do other stuff with $row
}

To make it work, you need a PHP function called mysql_data_seek, below is the way to use it

$sql = "SELECT * from table ORDER BY RAND()";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
// do stuff with $row
}

mysql_data_seek($result, 0);

while ($row = mysql_fetch_assoc($result)) {
// do other stuff with $row
}


Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

2 Comments so far

  1. m0dk1d on June 5, 2008 9:19 am

    Brilliant! I have a website needs exactly this function.

  2. stanley on October 16, 2008 9:40 pm

    Thank you…!!

    It works great =D

Sponsors




Links