2011-11-18 51 views
2

我有一個問題。比方說,我有一個關係表「ClientInvoices」這種結構:使用一個查詢從mysql表創建帶有rowspan的html表?

 
id | id_client | id_invoice 
1   1   1 
2   1   2 
3   2   3 
4   3   4 
5   1   5    

你可以看到,客戶端1,有3張發票。每個客戶可以有多個發票,我將這些信息提取出來並放在html表中,如下所示:

 

CLIENT | INVOICES 
      1 
    1  2 
      5 
    2  3 
    3  4 

我該怎麼做?我知道很簡單,但我認爲我卡住了。我怎樣才能計算rowspawn,並只顯示一個包含所有發票的客戶?

回答

0

不要在力的SQL方面做!

SQL =數據(數據= HTML!)

1 - 與SQL

2選擇你的數據 - 用php

3加載您的數據 - 把你的數據,你想用的形式php/html

SQL並未創建用於選擇數據的html代碼,而是使用這些工具來創建它們。

5

不錯的問題,通過計算髮票來計算rowspan。這是我想出的代碼:

<?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> 

這會根據您的需要生成一張表。如果有什麼你不明白的,評論,我會解釋

+0

非常感謝你,真相! – Andrew