使用MySQL数据填充HTML表的列和行

时间:2019-01-04 19:33:29

标签: php html mysqli html-table

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

enter image description here

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

<? $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表格式的表,但是我想实现的是:

enter image description here

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

1 个答案:

答案 0 :(得分:1)

使用mysqli_fetch_row。每行都是一个可以通过索引访问的数组。看起来像:Array ( [0] => A [1] => 1 [2] => 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>