简体   繁体   中英

How to display value against foreign key from parent table?

I have 2 tables makers and cars.

makers have 2 columns make_id & make.make_id of this table is used as foreign key

in cars table.cars table have 3 columns car_id,make_id,price.

Now i want to show the values against make_id in makers table. Now its not displaying value it just display 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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