0

I want to use a query result multiple times.

$result=mysql_query("Select field from tables;");

while($result_details = mysql_fetch_array($result))
  { echo $result_details[0]; //Returns 10 Rows..
}

but if I use mysql_fetch_array($result) again its not returning rows.. I don't want to execute the same query multiple times Please let me know how to use the results of a query multiple times.

logan
  • 7,946
  • 36
  • 114
  • 185
  • Warning: The `mysql_xxx()` functions have been considered bad practice for a very long time, and are now formally deprecated. If at all possible, you should change your code to use the `mysqli_xx()` functions or the PDO library. – Spudley Jan 20 '13 at 11:14
  • @Spudley : may i know what is the reason ? – logan Jan 20 '13 at 11:35
  • I suggest you read this: [Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – Spudley Jan 20 '13 at 14:55

3 Answers3

2

First fetch all records using a while loop:

$result=mysql_query("Select field from tables;");
while($result_details = mysql_fetch_array($result))
{
    $var[]=$result_details;
}

Then display all using a foreach loop and a single variable $var anywhere in the same page where you used query or put query in a functions.php file and include and use anywhere:

foreach ($var as $value) {
    $value['field'];
}
julienc
  • 19,087
  • 17
  • 82
  • 82
Azim
  • 29
  • 4
2

If you do not want to make multiple queries then simply unwind the pointer to the desired position.After you execute your code.You should call function to seek to initial (0) position:

$result=mysql_query("Select field from tables;");

    while($result_details = mysql_fetch_array($result))
      { echo $result_details[0]; //Returns 10 Rows..
    }
        mysqli_data_seek($result ,0);
P S
  • 435
  • 1
  • 8
  • 26
1

You need to "rewind" result pointer using: http://php.net/manual/en/function.mysql-data-seek.php

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141