Apr
20
PHP Query one time PHP Repeat MySQL Array from Same Query
April 20, 2008 |
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
2 Comments so far



































Brilliant! I have a website needs exactly this function.
Thank you…!!
It works great =D