繁体   English   中英

PHP while():三次后如何停止?

[英]PHP while(): how to stop after three times?

我正在尝试创建一个PHP照片库(是的,我已经尝试过其他解决方案,没有使用我想要的设置)并且我试图while循环停止三次后进行此操作,因为我想要显示三个缩略图表格行。 这是我目前的代码:

<table>
<tr>
<?php while($row2 = mysql_fetch_assoc($result)) { echo "
<td><a href='URL/".$row2['file']."'><img src='URL/".$row2['file']."' width='200' height='106' /></a></td>
"; } ?>
</tr>
</table>

我不记得有关停止PHP循环的任何知识,所以请帮忙! 非常感谢。

所以你真正想要的是每行3张图片。 我认为这会奏效:

<table>
  <?php 
    $i = 0;
    while($row2 = mysql_fetch_assoc($result)) { 
      if($i%3==0)
        echo "<tr>"; 
      echo "<td><a href='URL/".$row2['file']."'><img src='URL/".$row2['file']."' width='200' height='106' /></a></td>";
      if($i%3==2)
        echo "</tr>";
      $i++;
    }
    if($i%3!=0)
      echo "</tr>";
  ?>
</table>
<table>
<tr>
<?php 
$i=1;
while($row2 = mysql_fetch_assoc($result)) { echo "
<td><a href='URL/".$row2['file']."'><img src='URL/".$row2['file']."' width='200' height='106' /></a></td>
"; 
if($i>=3) break;
$i++;

} ?>
</tr>
</table>

尝试在while中添加AND并与计数器进行比较($ row2 = mysql_fetch_assoc($ result)&& $ i <3)

在循环之前将$ i设置为0

为什么不限制原始MySQL查询中返回的结果? 您可以像这样为查询添加限制:

limit 3

这样$ result只会有三行,因此不需要额外的PHP和内存中DB的数据

你可以添加一个计数器,如:

$nr = 1;
while($row2 = mysql_fetch_assoc($result)) { 
if ($nr < 4) {
do your thing;
}
$nr++;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM