简体   繁体   English

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

[英]How to display value against foreign key from parent table?

I have 2 tables makers and cars. 我有2个桌子制造商和汽车。

makers have 2 columns make_id & make.make_id of this table is used as foreign key 制造商有2列该表的make_id和make.make_id用作外键

in cars table.cars table have 3 columns car_id,make_id,price. 在cars table.cars表中有3列car_id,make_id,price。

Now i want to show the values against make_id in makers table. 现在,我想在maker表中显示针对make_id的值。 Now its not displaying value it just display 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();
        ?>

Change your query to this: 将查询更改为此:

$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";

You are working with two tables (cars and makers) that are connected via a foreign key. 您正在使用通过外键连接的两个表(汽车和制造商)。 So, you have to use the JOIN query to select columns from both tables and map the foreign key on cars table to the primary key on makers table (in your case, make_id on cars table and make_id on makers table) that match on both tables using the ON keyword. 因此,您必须使用JOIN查询从两个表中选择列,并将cars表上的外键映射到maker表上的主键(在您的情况下,cars表上的make_id和maker表上的make_id)都匹配使用ON关键字。

Your new code should now look like this: 您的新代码现在应如下所示:

<?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();
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM