19

a simple

$stuff = mysql_query("SELECT * FROM users");

while($s = mysql_fetch_array($stuff)){
# ....
}

while($r = mysql_fetch_array($stuff)){
# ...
}

The last while() does not work. I have tried run foreach($stuff as $s) but then i get invalid array error.

How can i use the same query twice?

2
  • I think that you need to reset the array to the beginning before trying to reuse it as you've reached the end from the first result set. Commented Nov 27, 2011 at 12:34
  • 3
    please, stop using the outdate mysql_* functions an learn how to use PDO and prepared statements. Commented Nov 27, 2011 at 12:39

5 Answers 5

43
$stuff = mysql_query("SELECT * FROM users");

while($s = mysql_fetch_array($stuff)){
# ....
}
// add this line
mysql_data_seek( $stuff, 0 );

while($r = mysql_fetch_array($stuff)){
# ...
}

Should do the trick

Another way is of course to store your result in an array and reuse that

Sign up to request clarification or add additional context in comments.

1 Comment

mysql_data_seek( $stuff, 0); Here is the manual : mysql_data_seek function
2
$stuff = mysql_query("SELECT * FROM users");

while($s = mysql_fetch_array($stuff)){
# ....
}
mysql_data_seek($stuff, 0);
while($r = mysql_fetch_array($stuff)){
# ...
}
//ref: http://www.php.net/manual/en/function.mysql-data-seek.php

Comments

0

see the docs

I guess it's because

Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

I think moving data pointer with mysql_data_seek() would do the job But i think this is not a good way, you should usually fetch data from database once and store them

1 Comment

yes I know that, I just wanted to say that it's better to use result once if possible
0

If you user "foreach" instead of "while" you'll not have any problem and no need to mysqli_seek_data() :

//1st loop :
foreach($stuff as $row)
{
   echo $row['...'];
}
...
//2nd loop :
foreach($stuff as $row)
{
   echo $row['...'];
}

Comments

0

Here is another simpler solution:

$slq = "SELECT * FROM users";

$stuff1 = mysql_query($slq);

while($s = mysql_fetch_array($stuff1)){
# ....
}

$stuff2 = mysql_query($slq);

while($r = mysql_fetch_array($stuff2)){
# ...
}

Assign the sql to a variable, and call mysql multiple times.

no more mysql. use mysqli or pdo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.