我是 php 编程的新手,我在使用 php 和 html 显示 mysql 数据库中的数据时遇到了一些问题。这是我的桌子:
location :id_location
location
component :id_comopnent
id_location
comonen
sub_component :id_sub_component
id_comopnent
sub_component
我怎样才能得到以下输出:
location
|-----------|-------------|
| component |sub component|
|-----------|-------------|
| | Data |
| Data |-------------|
| | Data |
|-----------|-------------|
| | Data |
| |-------------|
| Data | Data |
| |-------------|
| | Data |
|-----------|-------------|
location
|-----------|-------------|
| component |sub component|
|-----------|-------------|
| | Data |
| Data |-------------|
| | Data |
|-----------|-------------|
| | Data |
| Data |-------------|
| | Data |
|-----------|-------------|
Location (according to the data)
这是我的代码
<?php
$dsn = "mysql:host=localhost;dbname=kampus_hijau";
$dbc = new PDO($dsn, 'root', '');
$sql1 = "SELECT * FROM Lokasi ORDER BY id_location";
$stmt1 = $dbc->prepare($sql1);
$stmt1->execute();
while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)) {
$location++;
echo "Location $location : ".$row1['location'];
?>
<table width="469" border="1">
<tr bgcolor="#00FFFF">
<th width="109" class="rounded" scope="col">Component</th>
<th width="248" class="rounded" scope="col">Sub Component</th>
<th>Nilai</th>
</tr>
<?php
$query = "SELECT * FROM sub_component,component where sub_component.id_component=component.id_component and component.id_location='$data[id_location]' order by component.id_location";
$stmt = $dbc->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['component']][] = $row['sub_component'];
}
foreach($result as $id => $invoices) {
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++;
}
}
?>
</table>
<?php
}
?>
这是我得到的输出:
使用该代码,输出形式是合适的,但数据似乎不合适,它总是在下一个表中显示之前的数据(红色框是重复的数据)。我该如何解决?