使用一个查询从mysql表创建带有rowspan的html表? [英] Create html table with rowspan from mysql table with one query?

查看:106
本文介绍了使用一个查询从mysql表创建带有rowspan的html表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a question. Let's say I have a relational table "ClientInvoices" with this structure:


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

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

You can see that CLIENT 1, have 3 invoices. Each client can have multiple invoices, and I to extract this information and put it in an html table, like this:



CLIENT | INVOICES
            1
    1       2
            5
    2       3
    3       4

我该怎么做?我知道很简单,但我觉得我被卡住了。如何计算rowspawn,并且只显示一个包含所有发票的客户?

How can I do that? I know is very simple, but I think I'm stuck. How can I calculate rowspawn, and show only one client with all invoices for him?

推荐答案

不错的问题,行数的计算是通过计算发票来完成。这是我提出的代码:

Nice question, the calculation of rowspan is done by counting the invoices. Here's the code I came up with:

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

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

This generates a table as you require. If there's something you don't understand, comment and I'll explain

这篇关于使用一个查询从mysql表创建带有rowspan的html表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆