重置while循环

时间:2010-12-28 16:38:34

标签: php javascript

我在php脚本中发现了一个令人困惑的事情,我正在编写生成一些javascript。它在下面,略微简化。

第二个while循环不会运行,除非我注释掉整个第一个while循环。有谁能解释为什么?非常感谢。

<?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++;
}
?>

2 个答案:

答案 0 :(得分:4)

您尚未复制结果集,您最终只有两个引用到结果集。无论您使用哪个引用,基础结果集对象都是相同的,因此您已经在第二个循环开始时处理了所有记录。

您可能希望切换到使用单个循环,并跟踪要在数组中输出的数据。或者as Flinsch points out,您可以使用mysql_data_seek返回结果集的开头,因为您正在使用缓冲查询。

答案 1 :(得分:3)

除了what T.J. Crowder already said之外,mysql_data_seek($result1, 0)将在两个循环之间完成工作,以重置内部迭代器。