【问题标题】:Create html table with rowspan from mysql table with one query?使用一个查询从 mysql 表创建具有行跨度的 html 表?
【发布时间】:2012-01-01 01:43:24
【问题描述】:

我有一个问题。假设我有一个具有这种结构的关系表“ClientInvoices”:

编号 | id_client | id_invoice 1 1 1 2 1 2 3 2 3 4 3 4 5 1 5

您可以看到客户 1 有 3 张发票。每个客户可以有多个发票,我将这些信息提取出来并放在一个 html 表中,如下所示:

客户 |发票 1 1 2 5 2 3 3 4

我该怎么做?我知道这很简单,但我想我被卡住了。如何计算rowspawn,并只显示一个客户及其所有发票?

【问题讨论】:

    标签: php mysql html-table


    【解决方案1】:

    不要在强制的 SQL 端这样做!!

    SQL = 数据(数据!= html)

    1 - 使用 sql 选择您的数据

    2 - 使用 php 加载数据

    3 - 使用 php / html 将您的数据以您想要的形式放置

    SQL 不是为创建 html 代码而设计的,它是为选择数据而设计的,使用工具来实现它们的目的。

    【讨论】:

      【解决方案2】:

      很好的问题,行跨度的计算是通过计算发票来完成的。这是我想出的代码:

      <?php
      
          /**
           * @author Truth
           * @copyright 2011
           */
      
          $dsn = "mysql:host=localhost;dbname=test";
          $dbc = new PDO($dsn, 'root', 'pass');
      
          $query = 'SELECT * FROM invoice';
          $stmt = $dbc->prepare($query);
          $stmt->execute();
      
          while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
              $result[$row['client_id']][] = $row['invoice_id'];
          }
      
      ?>
      <!DOCTYPE html>
      <html>
      
          <head>
              <!-- Metas -->
              <meta http-equiv="content-type" content="utf-8" />
              <meta name="author" content="Truth" />
      
              <title>Invoice Rowspan Example</title>
      
          </head>
      
          <body>
      
              <table id="invoices" border="1">
                  <thead>
                      <th>Client</th>
                      <th>Invoices</th>
                  </thead>
                  <tbody>
                      <?php
      
                          foreach($result as $id => $invoices) {
                              echo '<tr>';
                              echo '<td rowspan='. count($invoices) . '>' . $id . '</td>';
                              $count = 0;
                              foreach ($invoices as $invoice) {
                                  if ($count != 0) {
                                      echo '<tr>';
                                  }
                                  echo "<td>$invoice</td>";
                                  echo "</tr>";
                                  $count++;
                              }
                          }
      
                      ?>
                  </tbody>
              </table>
      
          </body>
      </html>
      

      这会根据您的需要生成一个表格。如果有不明白的地方,请评论,我会解释的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-07
        • 2016-02-29
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多