我正在尝试将两个表中的数据添加到我的PHP网站。数据应采用表格布局。表'bikes'正在使用制造商表中的ID
<?php
echo '<table>';
echo '<thead>';
echo '<tr>';
echo '<th>Model</th>';
echo '<th>condition</th>';
echo '<th style="width: 10%">Price</th>';
echo '<th style="width: 5%"> </th>';
echo '<th style="width: 5%"> </th>';
echo '</tr>';
$products = $pdo->query('SELECT * FROM bikes');
foreach ($products as $product) {
echo '<tr>';
echo '<td>' . $product['model'] . '</td>';
echo '<td>' . $product['condition'] . '</td>';
echo '<td>£' . $product['price'] . '</td>';
echo '<td><a style="float: right" href="editbike.php?id=' . $product['id'] . '">Edit</a></td>';
echo '<td><form method="post" action="deletebike.php">
<input type="hidden" name="bikeId" value="' . $product['id'] . '" />
<input type="submit" name="submit" value="Delete" />
</form></td>';
echo '</tr>';
}
echo '</thead>';
echo '</table>';
}
else {
?>
另一个表叫做制造商......有没有办法可以将制造商表中的数据添加到网站,数据彼此相邻,因为这看起来像表布局? (如果不确定我的意思是添加电子邮件和电子邮件截图我正在尝试做什么)
答案 0 :(得分:-1)
您需要在2个表之间创建关系,例如将manufacturer_id
添加到bikes
表格。
然后,您可以在两个表中进行选择:
$products = $pdo->query('SELECT b.*, m.* FROM bikes AS b, manufacturers AS m WHERE m.id = b.manufacturer_id');
$products = $pdo->query('SELECT b.*, m.* FROM bikes AS b JOIN manufacturers AS m ON m.id = b.manufacturer_id');
如果这些表共享列名,例如'name',那么您需要为其中一个别名:
$products = $pdo->query('SELECT b.*, m.*, m.name AS manufacturer_name FROM bikes AS b JOIN manufacturers AS m ON m.id = b.manufacturer_id');
$products['name'] = 'bike name';
$products['manufacturer_name'] = 'manufacturer name';
任何时候两列具有相同的名称,第一个选择将优先,在上述情况下bikes
将优先,如果您反转选择制造商将优先:
$products = $pdo->query('SELECT m.*, b.*, m.name AS manufacturer_name FROM bikes AS b JOIN manufacturers AS m ON m.id = b.manufacturer_id');
$products['name'] = 'manufacturer name';
$products['manufacturer_name'] = 'manufacturer name';