【问题标题】:Populating columns and rows of HTML table with MySQL data使用 MySQL 数据填充 HTML 表的列和行
【发布时间】:2019-01-05 07:26:26
【问题描述】:

不知道如何很好地表达这个问题,但希望有人能提供帮助...我正在尝试从 MySQL 数据库中选择数据并使用 PHP 将其输出到 HTML 表中,查询中的数据形成列标题和行.我的“预算”表中的数据如下所示:

我想在行中输出客户,在列中输出周,并将数量的总和作为数据输出。到目前为止,我有:

<? $q1 = mysqli_query($conn, "SELECT customer, week, sum(qty) AS qty FROM budget GROUP BY week, customer"); ?>
<table>
    <thead>
        <tr>
            <th>Customer</th>
            <th>Week</th>
            <th>Qty</th>
        </tr>
    </thead>
    <tbody>
    <? while($row1 = mysqli_fetch_assoc($q1)){ ?>
        <tr>
            <td><?= $row1['customer']; ?></td>
            <td><?= $row1['week']; ?></td>
            <td><?= $row1['qty']; ?></td>
        </tr>
    <? } ?>
    </tbody>
</table>

这会产生一个类似于原始 MySQL 表格式的表,但我想要实现的是:

周选择将是动态的,因此我希望在列中显示 4 或 36 周,具体取决于它们在表单中的选择。

【问题讨论】:

    标签: php html mysqli html-table


    【解决方案1】:

    mysqli_fetch_row。每行都是一个可以通过索引访问的数组。看起来像:Array ( [0] =&gt; A [1] =&gt; 1 [2] =&gt; 52 ... )

    创建一个新的二维数组,看起来像

    $arr["A"] = [
      1 => ...
      2 => ...
    ]
    

    示例

    PHP

    <?php
    
    // $conn = ...
    $q1 = mysqli_query($conn, "SELECT customer, week, sum(qty) AS qty FROM budget GROUP BY week, customer");
    $res1 = [];
    
    while($row = mysqli_fetch_row($q1)) 
    {
        array_push($res1, $row);
    }
    
    $title = "Customer";
    $max = $res1[count($res1) - 1][1];
    $res2 = [];
    // Index for "title" ("A", "B", "C", ...)
    $i = 0;
    
    foreach ($res1 as $row) {
        $res2[$row[$i]][$row[1]] = $row[2];
    }
    
    ?>
    

    HTML

    <table>
        <thead>
            <tr>
                <td><?= $title ?></td>
                <?php for ($i = 1; $i <= $max; $i++): ?>
                    <td><?= $i ?></td>
                <?php endfor; ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($res2 as $key => $values): ?>
                <tr>
                    <td><?= $key ?></td>
                    <?php foreach ($values as $value): ?>
                        <td><?= $value ?></td>
                    <?php endforeach; ?>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 2018-03-12
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      相关资源
      最近更新 更多