【问题标题】:Print database data in html Table在 html Table 中打印数据库数据
【发布时间】:2010-02-13 21:20:06
【问题描述】:

我知道如何在 html 表上打印数据库中的数据,但我有一项任务我无法理解,而且我做不到。 我在数据库中有一个表,当我选择这些数据时,我希望它们显示在 html 表上,但类似这样:

Image http://img683.imageshack.us/img683/9350/tablea.png

【问题讨论】:

    标签: php mysql html


    【解决方案1】:

    要实现这样的表格布局,您只需要调整表格行末尾的位置即可。

    <table>
      <tr>
    <?php
      $count = 0;
      while($row = mysql_fetch_assoc($result)) :
        $count++;
    ?>
        <td><?php echo $row['value'] ?></td>
    <?php if($count % 2 == 0 || $count == mysql_num_rows($res)) : ?>
      </tr>
    <?php if($count != mysql_num_rows($result)) : ?>
      <tr>
    <?php endif; ?>
    <?php endif; ?>
    <?php endwhile; ?>
    </table>
    

    上面的操作是使用模运算符(%,计算除法的余数)来打印一个结束和开始的行标签,只要我们得到一个偶数的结果。

    此外,如果您想将表格布局更改为 3 或 4 列宽,您只需更改应用于模数的数字:

    $count % 3 == 0 //3 columns
    $count % 4 == 0 //4 columns, etc
    

    【讨论】:

      【解决方案2】:
      <table>
          <?php while (TRUE) { ?>
              <?php
                  // Make an array of n rows. Trailing items may be FALSE if there
                  // are not enough rows to fill the table row.
                  //
                  $rows= array();
                  for ($i= 0; $i<n; $i++)
                      $rows[$i]= mysql_fetch_assoc($result);
                  if (!$row[0])
                      break;
              ?>
              <tr>
                  <?php foreach ($rows as $row) { ?>
                      <td>
                          <?php if ($row) { ?>
                              Value: <?php echo(htmlspecialchars($row['value']); ?>
                          <?php } ?>
                      </td>
                  <?php } ?>
              </tr>
          <?php } ?>
      </table>
      

      【讨论】:

      • 意大利面条编码的好例子
      • 你在说什么?这是一个单一的一致标记树,与“意大利面条代码”正好相反。你可以从缩进中准确地看到每个元素和 PHP 结构的开始和结束位置,这使得它比隐藏在一大块 PHP 中的随机 echos 更易于维护。
      • 我认为如果在解析和输出模式之间使用更少的切换,它的可读性会更高。我阅读了您的“正确的 PHP 教程”(stackoverflow.com/questions/2119083/…) 问题,我同意您的观点,除了一件事:从一开始就教刚接触该语言的人使用模板系统。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      • 2016-06-12
      相关资源
      最近更新 更多