php虽然mysql_fetch_array在里面

时间:2011-10-21 12:53:00

标签: php mysql while-loop

我有这部分代码,我无法理解为什么第一个循环内部的第二个循环不起作用。我查询了两个表,并在第二个表中放置了一个echo,看它是否回声,但它也没有。提前谢谢

while($row = mysql_fetch_array($result))
{
 echo "<li class=\"s01\"><a class=\"s03\" href=" . $row['link'] . "><span>". $row['onomaselidas'] ."</span></a>\n";
 echo "<ul class=\"pn2\">\n";
 $idd[]=$row['idwebsiteprimary'];
   while($row2 = mysql_fetch_array($result2))
   {
    echo "test";
   if($idd[$url]==$row2['idwebsite'])
    {
    echo "<li class=\"s01\"><a href=\"a\"><span>". $row2['name'] ."</span></a></li>\n";
    }
   }
 echo "</ul>\n";
}

1 个答案:

答案 0 :(得分:0)

在第一次循环的第一次迭代之后,第二个结果集的内部指针位于结尾,因此第二个循环将不会执行,因为mysql_fetch_array()将立即返回false。如果你想完全如上所述 - 第二个结果集不依赖于第一个 - 你需要这样做:

// First, get the results of set 2 into an array
$resultset2 = array();
while ($row = mysql_fetch_assoc($result2)) $resultset2[] = $row;

while ($row = mysql_fetch_assoc($result)) { // Do your thang
  echo "<li class=\"s01\"><a class=\"s03\" href=" . $row['link'] . "><span>".$row['onomaselidas'] ."</span></a>\n";
  echo "<ul class=\"pn2\">\n";
  $idd[] = $row['idwebsiteprimary'];
  foreach ($resultset2 as $row2) { // Foreach sets it's pointer to the beginning every time, so this should work
    echo "test";
    if ($idd[$url]==$row2['idwebsite']) {
      echo "<li class=\"s01\"><a href=\"a\"><span>". $row2['name'] ."</span></a></li>\n";
    }
  }
  echo "</ul>\n";
}

或者,您可以通过调用mysql_data_seek($result2, 0);来重置第一个循环的每次迭代的$result2的内部指针:

while ($row = mysql_fetch_array($result)) {
  echo "<li class=\"s01\"><a class=\"s03\" href=" . $row['link'] . "><span>". $row['onomaselidas'] ."</span></a>\n";
  echo "<ul class=\"pn2\">\n";
  $idd[] = $row['idwebsiteprimary'];
  mysql_data_seek($result2, 0);
  while ($row2 = mysql_fetch_array($result2)) {
    echo "test";
    if($idd[$url]==$row2['idwebsite']) {
      echo "<li class=\"s01\"><a href=\"a\"><span>". $row2['name'] ."</span></a></li>\n";
    }
  }
  echo "</ul>\n";
}