PHP循环增加数字

时间:2013-06-15 20:10:05

标签: php loops foreach

我有这段代码:

<?php
$i=1;
while($i<=10)
  {
  echo "" . $i . "<br>";
  $i++;
  }
?>

列为:

1 2 3 4 五 6 7 8 9 10

我正在尝试将echo "" . $i . "<br>";实现到<td>单元格中:

<table>
<?php 
$data = mysql_query("SELECT board.*,numlikes FROM board
LEFT JOIN (SELECT pins.board_id, COUNT(source_user_id) AS numlikes
FROM likes INNER JOIN pins ON pins.id = likes.pin_id GROUP BY pins.board_id) 
likes ON board.id = likes.board_id
WHERE who_can_tag='' ORDER BY numlikes DESC LIMIT 10") or die(mysql_error());
while($info = mysql_fetch_assoc( $data ))
{
Print "<tr>";
Print "<td>";
Print "$i";
Print "</td>";
Print "<td>";
Print "<a href='/board/index/".$info['id']."'><font size='5pt'>".$info['board_name']."</font></a>";
Print "</td>";
Print "<td align='center'>".$info['numlikes']."</td>";
Print "</tr>";

}

?>
</table>

但我得到的只是每个单元格的数字11!

我做错了什么?

3 个答案:

答案 0 :(得分:1)

你忘记了:

$i++;

线。你必须先将$ i设置为0或1。

答案 1 :(得分:1)

是的,你的第二个代码中没有增加$i。所以用$i++增加它:

$i = 1;
while ($info = mysql_fetch_assoc( $data ))
{
    // ...
    print "<td>";
    print $i++;
    print "</td>";
   //...
}

另外,首先初始化您的$i,这样您就可以确定它之前没有设置过。

答案 2 :(得分:1)

您没有在while loop中增加变量。

您需要声明$i并在循环中递增它,例如:

$i = 1;
while($info = mysql_fetch_assoc( $data ))
{
   print "<tr>";
   print "<td>";
   print "$i";
   print "</td>";
   print "<td>";
   print "<a href='/board/index/".$info['id']."'><font size='5pt'>".$info['board_name']."</font></a>";
   print "</td>";
   print "<td align='center'>".$info['numlikes']."</td>";
   print "</tr>";

   $i++;
}