sql >> Database >  >> RDS >> Mysql

HTML-tabel maken met rowspan van mysql-tabel met één query?

Leuke vraag, de berekening van rowspan doe je door de facturen te tellen. Dit is de code die ik heb bedacht:

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

Dit genereert een tabel zoals u dat wenst. Als je iets niet begrijpt, reageer dan en ik zal het uitleggen



  1. JSON invoegen in een tabel in SQL Server

  2. Databaseprobleem, hoe de veranderende gegevensstructuur op te slaan?

  3. Entity Framework Initiële gegevens invoegen bij opnieuw opbouwen

  4. Een SQLite-database herstellen