mckeegan375
mckeegan375

Reputation: 255

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. The data in my 'budget' table looks like:

enter image description here

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:

enter image description here

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.

Upvotes: 0

Views: 753

Answers (1)

user3589620
user3589620

Reputation:

With mysqli_fetch_row. Each row is an array that can be accessed by indices. It looks like: Array ( [0] => A [1] => 1 [2] => 52 ... )

Create a new two dimensional array that looks like

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

Example

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>

Upvotes: 1

Related Questions