[英]MySQL using PHP join a table to another
我需要一點幫助,因為我不知道如何將一個表連接到另一個表。 我想在機器表中從客戶表中輸出所有者的姓名,而不是輸出客戶 ID。 如果是 full_name,則在 clients 表所有者的名稱中。
<table class="tbl-full" id="clients">
<tr>
<th>ID</th>
<th>VIN</th>
<th>Model</th>
<th>Client ID</th>
<th>Desc</th>
<th>Make</th>
<th>Year</th>
<th>Actions</th>
</tr>
<?php
$sql = "SELECT * FROM machines ORDER BY year DESC";
$res = mysqli_query($conn, $sql);
if ($res == TRUE) {
$count = mysqli_num_rows($res);
$sn = 1;
if ($count > 0) {
while ($rows = mysqli_fetch_assoc($res)) {
$id = $rows['id'];
$vin = $rows['vin'];
$client_id = $rows['client_id'];
$model = $rows['model'];
$description = $rows['description'];
$make = $rows['make'];
$year = $rows['year'];
?>
<tr>
<td><?php echo $sn++; ?></td>
<td><?php echo $vin; ?></td>
<td><?php echo $model; ?></td>
<td><?php echo $client_id; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $make; ?></td>
<td><?php echo $year; ?></td>
<td>
<a href="<?php echo SITEURL; ?>/update-machine.php?id=<?php echo $id; ?>" class="main-btn">Update Machine</a>
<a href="<?php echo SITEURL; ?>/delete-machine.php?id=<?php echo $id; ?>" class="danger-btn">Delete Machine</a>
</td>
</tr>
$sql = "SELECT m.*, c.full_name AS 'client_full_name'
FROM machines m
LEFT JOIN clients c ON c.id = m.client_id
ORDER BY m.year DESC";
然后
$client_full_name = $rows['client_full_name'];
最后
<td><?php echo $client_full_name; ?></td>
您的查詢應該是這樣的
SELECT M.*,C.full_name
FROM machines as m
INNER JOIN clients as c ON m.id = c.client_id
ORDER By m.year DESC
然后使用
$client_name = $row['client_name']
然后回顯客戶端名稱
<td><?php echo $client_name; ?></td>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.