Resetting a while loop
I have found a confusing thing in a php script I am writing to generate some javascript. Here it is below, slightly simplified.
The second while loop won't run unless I comme开发者_运维百科nt out the entire first while loop. Can anyone explain why? Many thanks.
<?php
$listid = 2; //DEMO ONLY
$result1 = mysql_query("SELECT words.wid,words.wordmd5,words.word FROM words,instances WHERE words.wid = instances.wid AND instances.lid = \"$listid\"");
$result1copy = $result1;
$count1 = 1;
while( $row = mysql_fetch_object( $result1 ) )
{
print "words_left[$count1] = \"".$row->word."\";\n";
//Increment the array counter (starts at 1)
$count1++;
}
?>
//Some javascript
<?php
$count2 = 1;
while( $row = mysql_fetch_object( $result1copy ) )
{
print "
$count2 then $row->wordmd5
";
$count2++;
}
?>
You haven't copied the result set, you've just ended up with two references to the result set. The underlying result set object is the same regardless of which reference to it you use, and so you've already processed all of the records by the time the second loop begins.
You probably want to switch to using a single loop, and keeping track of the data you want to output in an array. Alternately, as Flinsch points out, you could use mysql_data_seek
to return to the beginning of the result set, since you're using a buffered query.
In addition to what T.J. Crowder already said, a mysql_data_seek($result1, 0)
would do the job between the two loops, to reset the internal iterator.
精彩评论