我在MySql數據庫中有兩個表格,命名項目和類型,項目中有椅子,表格等。在類型我有木材和鐵。如何在單表格中打印多個表格中的值php
項目表
+--------+-----------+
| ItemID | Item_Name |
+--------+-----------+
| 1 | Chair |
| 2 | Table |
| 3 | Bed |
+--------+-----------+
類型表
+--------+-----------+
| TypeID | Item_Type |
+--------+-----------+
| 1 | Iron |
| 2 | Wood |
+--------+-----------+
現在我想在PHP表打印此如下,
新表
+------------+---------------+---------------+
| Item Name | Item Type One | Item Type Two |
+------------+---------------+---------------+
| Chair | Iron | Wood |
| Table | Iron | Wood |
| Bed | Iron | Wood |
+------------+---------------+---------------+
我試着此代碼:
<?php
$query_Item = $db->query("SELECT * FROM tb_Items");
$itemsRowCount = $query_Item->num_rows;
$query_Type = $db->query("SELECT * FROM tb_Types");
$typesRowCount = $query_Type->num_rows;
?>
<table border="1">
<tr>
<th>Item Name</th>
<th>Item Type One</th>
<th>Item Type Two</th>
</tr>
<?php
if($itemsRowCount > 0){
while($row = $query_Item->fetch_assoc()){
?>
<tr>
<td><?php echo $row['ItemName']; ?></td>
<?php
if($typesRowCount > 0){
while($row = $query_Type->fetch_assoc()){
?>
<td><?php echo $row['ItemType']; ?></td>
<?php
}
}
?>
</tr>
<?php
}
}
?>
</table>
但它給人的輸出是這樣的:
+-----------+---------------+---------------+
| Item Name | Item Type One | Item Type Two |
+-----------+---------------+---------------+
| Chair | Iron | Wood |
| Table | | |
| Bed | | |
+-----------+---------------+---------------+
只打印時,因爲它應該是第一行。 問題是什麼?我怎樣才能做到這一點?