0

The first loop does well,but the second isn't. For example:

$sql = "select * from table";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
  //some code
}
while($row=mysql_fetch_array($result))
{
  //some code
}

I just want to know why

3 Answers 3

1

after I answered I've done some more research and posted the correct version in the edit below

Because it's the way array iterators work in PHP, resetting the pointer should do the trick:

while($row=mysql_fetch_array($result))
{
  //some code
}
// reset($result); - won't work with mysql_query() result
mysql_data_seek($result, 0);
while($row=mysql_fetch_array($result))
{
   //some code
}

Read more on the reset() function here

EDIT: after more research I found I was wrong - use mysql_data_seek:

mysql_data_seek($result, 0);
Sign up to request clarification or add additional context in comments.

3 Comments

This is not correct, reset() accepts array, here you provided resource because $result is resource (return of mysql_query)
@JasonOOO Sorry, I have updated my answer, just found this out myself
Warning: reset() [function.reset]: Passed variable is not an array or object
1

Once you fetch all data of result set through first while loop then pointer goes to the last record and thus it won't fetch anything in the second while loop. You need to set pointer back to the first record before passing it again to while loop.

Just update your code like this:

$sql = "select * from table";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
  //some code
}

mysql_data_seek(0); // Add this line

while($row=mysql_fetch_array($result))
{
  //some code
}

Comments

0

You can copy $result like this:

$sql = "select * from table";
$result=mysql_query($sql);
$result2 = $result;
while($row=mysql_fetch_array($result))
{
  //some code
}
while($row=mysql_fetch_array($result2))
{
  //some code
}

2 Comments

It should work, but I think it would be better to iterate over the $result and copying the content first to an array and not the result object
yes, but I think OP wants to know how to do that, copying to array is better

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.