【问题标题】:Table designing in while loop在while循环中设计表格
【发布时间】:2023-04-08 19:13:02
【问题描述】:

我想在一个表中显示来自数据库的 4 张图像 (2*2) 我知道该怎么做。但是我也有特殊情况(如果图片少于4张,会显示默认图片,总共显示4张)

我在一个while循环中管理它。如果有 4 张图像没有问题,它可以按我的意愿工作,但是当图像较少时(这意味着默认图像将总共完成 4 张图像),它就不起作用了。我不知道该怎么做。

有什么帮助吗?

<table>
<tr>
<?php                               
$todisplay = 4;

$query = mysql_query("select * from Images where Country_ID=$co_id LIMIT 0,4;");

while ($row = mysql_fetch_array($query)) {
$x++;
 echo "<td><img src='".$row['I1_Th'] .  "'/></td>";
 $displayed_number++;
 if ($x % 2==0) {
 echo "</tr><tr>";}
}   

echo str_repeat("<td>
<img src='images/png/defthumb.png'> </td>", $todisplay-$displayed_number);
?>
</tr></table>

【问题讨论】:

    标签: php while-loop html-table


    【解决方案1】:

    您离它不远了 - 只需创建另一个执行相同操作的循环,但使用默认图像。另外,$displayed_number 似乎与$x 保持相同的值,所以我删除了它。

    <table>
    <tr>
    <?php                               
    $todisplay = 4;
    
    $query = mysql_query("select * from Images where Country_ID=$co_id LIMIT 0,4;");
    $x = 0;
    
    while ($row = mysql_fetch_array($query)) {
    $x++;
     echo "<td><img src='".$row['I1_Th'] .  "'/></td>";
    
     if ($x % 2==0) {
     echo "</tr><tr>";}
    }   
    
    while ( $x < $todisplay) {
    $x++;
     echo "<td><img src='images/png/defthumb.png'/></td>";
     if ($x % 2==0) {
     echo "</tr><tr>";}
    }   
    ?>
    </tr></table>
    

    【讨论】:

    • 亲爱的 Tudor,此代码生成 2*2 表格,但默认图片再次在行下方显示 4 次。
    【解决方案2】:

    与其对查询返回的行进行循环,不如直接循环四次并尝试获取一行?

    <table>
    <tr>
    <?php                               
    $tablerows = 2;
    
    $query = mysql_query("select * from Images where Country_ID=$co_id LIMIT " + ($tablerows * 2) + ";");
    
    for ($x = 1; $x <= ($tablerows * 2); $x++) {
      if ($row = mysql_fetch_array($query)) {
        echo "<td><img src='".$row['I1_Th'] .  "'/></td>";
      } else {
        echo "<td><img src='images/png/defthumb.png'></td>";
      }
      if ($x % 2==0 && $x != $tablerows * 2) {
        echo "</tr><tr>";}
    }
    ?>
    </tr></table>
    

    【讨论】:

    • 谢谢!像魅力一样工作。
    • 您可能希望使用变量来确定行数(而不是要显示的图像数),以确保每行始终有两列,例如我上面的更新。
    猜你喜欢
    • 2013-03-07
    • 2015-01-04
    • 1970-01-01
    • 2011-06-02
    • 2013-03-28
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    相关资源
    最近更新 更多