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.

3
  • 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. Commented Jan 20, 2013 at 11:14
  • @Spudley : may i know what is the reason ? Commented Jan 20, 2013 at 11:35
  • I suggest you read this: Why shouldn't I use mysql_* functions in PHP? Commented Jan 20, 2013 at 14:55

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

Comments

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'];
}

Comments

1

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

3 Comments

You meant to say ? mysql_free_result($result);
No. I meant exactly what I wrote in my answer. mysql_data_seek(). If you free your result you'd not be able to do anything with it any more.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.