如何显示来自父表的外键值?

时间:2018-08-25 09:44:41

标签: php

我有2个桌子制造商和汽车。

制造商有2列make_id和make.make_id将此表用作外键

在cars表中。cars表有3列car_id,make_id,price。

现在我想在maker表中显示针对make_id的值。现在它不显示值,只显示id。

<?php
        $conn=mysqli_connect("localhost","root","","practice");
        if($conn-> connect_error){
        die("Connection field:". $conn-> connection_error);
    }$sql="SELECT car_id,make_id,price from cars ";
    $result=$conn->query($sql);
   if($result->num_rows>0){
   while($row=$result->fetch_assoc()){
   echo"<tr><td>".$row["car_id"]."</td><td>".$row["make_id"]."</td> 
   <td>".$row["price"]."</td></tr>";
   }
   echo"</table>";
   }else {
   echo"0 result";
   }
    $conn->close();
        ?>

1 个答案:

答案 0 :(得分:1)

将查询更改为此:

$sql = "SELECT c.car_id, m.make, c.price 
        FROM cars AS c JOIN makers AS m ON c.make_id = m.make_id ORDER BY c.car_id";

您正在使用通过外键连接的两个桌子(汽车和制造商)。因此,您必须使用JOIN查询从两个表中选择列,并将cars表上的外键映射到maker表上的主键(在您的情况下,cars表上的make_id和maker表上的make_id)都匹配使用ON关键字。

您的新代码现在应如下所示:

<?php
    $conn = mysqli_connect("localhost", "root", "", "practice");
    if ($conn->connect_error) {
        die("Connection field:" . $conn->connection_error);
    }
    $sql = "SELECT c.car_id, m.make, c.price FROM cars AS c JOIN makers AS m ON c.make_id = m.make_id ORDER BY c.car_id";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo "<tr><td>" . $row["car_id"] . "</td><td>" . $row["make"] . "</td>  // Notice that I changed $row['make_id'] to $row['make']
       <td>" . $row["price"] . "</td></tr>";
        }
        echo "</table>";
    } else {
        echo "0 result";
    }
    $conn->close();
?>