简体   繁体   English

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

[英]Populating columns and rows of HTML table with MySQL data

Not sure how to word this question well but hopefully someone can help... I'm trying to select data from a MySQL database and output it to a HTML table using PHP whereby data from the query forms the column headings and rows. 不确定如何很好地表达这个问题,但希望有人能提供帮助...我正在尝试从MySQL数据库中选择数据,然后使用PHP将其输出到HTML表中,从而查询中的数据形成列标题和行。 The data in my 'budget' table looks like: 我的“预算”表中的数据如下所示:

在此处输入图片说明

I want to output the Customer in the rows, Week in the columns and sum of the Qty as the data. 我想在行中输出“客户”,在列中输出“周”,并输出“数量总和”作为数据。 So far, I have: 到目前为止,我有:

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

This produces a table similar to the original MySQL table format but what i'm trying to achieve is: 这产生了一个类似于原始MySQL表格式的表,但是我想要实现的是:

在此处输入图片说明

The week selection will be dynamic so it could be 4 or 36 weeks that i'd want in the columns depending on their selection in a form. 周的选择将是动态的,因此我希望在列中输入4或36周的时间,具体取决于他们在表格中的选择。

With mysqli_fetch_row . 使用mysqli_fetch_row Each row is an array that can be accessed by indices. 每行都是一个可以通过索引访问的数组。 It looks like: Array ( [0] => A [1] => 1 [2] => 52 ... ) 看起来像: Array ( [0] => A [1] => 1 [2] => 52 ... )

Create a new two dimensional array that looks like 创建一个新的二维数组,看起来像

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

Example

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM