1

我正在尝试制作一个 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 循环的知识,所以请帮忙!将不胜感激。

4

5 回答 5

4

所以你真正想要的是每行 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>
于 2012-07-20T02:16:11.317 回答
1
<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>
于 2012-07-20T01:25:16.547 回答
0

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

limit 3

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

于 2012-07-20T01:33:20.450 回答
0

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

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

于 2012-07-20T01:29:23.413 回答
-1

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

$nr = 1;
while($row2 = mysql_fetch_assoc($result)) { 
if ($nr < 4) {
do your thing;
}
$nr++;
}
于 2012-07-20T01:25:44.907 回答