【问题标题】:PHP/MySQL Output Data in TD'sTD 中的 PHP/MySQL 输出数据
【发布时间】:2009-07-29 03:15:44
【问题描述】:

在查询数据库时,我将如何限制 HTML 表格列的数量。

例如,我有一个具有以下值的 MySQL 表:

myTable:
  id     color
   1      red
   2      blue
   3      green
   4      pink
   5      purple

当我运行查询时,而不是显示传统表格行中的所有行,例如

<table>
<?php
   while {
   echo "<tr><td>$row['color']</td></tr>;
         }
 ?>
</table>

相反,我想强加一些东西,每三个 td 就会创建一个新的 tr。

例如,它会输出如下内容:

<table>
  <tr>
  <td>red</td>
  <td>blue</td>
  <td>green</td>
  </tr>  <-- Notice how after 3 columns, a new table row is created.
  <tr>
  <td>pink</td>
  <td>purple</td>
  </tr>
  </table>

有什么方法可以做到这一点?

【问题讨论】:

    标签: php mysql html-table


    【解决方案1】:

    为了实现这一点,您可以使用计数器和modulus (%) 运算符的组合:

    <table>
    <?php
      $count = 0;
      while($row = mysql_fetch_array($results)) {
        $outputTr = ($count % 3) == 0;
    
        if($outputTr) echo '<tr>';
    
        echo '<td>' . $row['color'] . '</td>';
    
        if($outputTr) echo '</tr>';
    
        $count++;
      }
    ?>
    </table>
    

    【讨论】:

    • 那么,我们又在另一个问题上见面了。
    • 在得到我的 200 之前无法入睡!
    【解决方案2】:

    要实现这一点,请放置一个简单的计数器,每 3 个表数据重置一次。

    <?php
    echo "<table><tr>";
    $count = 0;
    foreach($data as $key => $color)
    {
        if($count == 3)
        {
            $count = 0;
            echo "</tr><tr>";
        }
        $count++;
        echo "<td>".$color."</td>";
    }
    echo "</tr></table>";
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-06
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多