簡體   English   中英

使用php顯示我數據庫中的相關記錄

[英]display related records from my database using php

我想基於其他表中的外鍵顯示與特定主鍵相關的記錄。 如何使用php在其他表中顯示該主鍵的記錄?

例如:

table1

primary key 1: plate#1
primary key 2: plate#2
primary key 3: plate#3

table2

primary key 1: destination|route|revenue|plate# 1
primary key 2: destination|route|revenue|plate# 3

table3

primary key 1: diesel price|number of liters|plate# 1

primary key 2: diesel price|number of liters|plate# 3

我已經創建了一個頁面,該頁面將顯示table1所有數據。 我想顯示在數據table1table2所涉及的數據table1 ,當我做了他們已經與對方的關系數據庫。 我的問題是僅顯示與table1相關的記錄。 我只想顯示plate#1記錄,另一個plate#2 ,依此類推。

您可能正在尋找聯接表以獲得最終結果的方法。 聯接使您可以將表合並在一起,並根據選擇獲得單個結果。 Google php mysql加入表並查看一些示例。 這是給您的: 連接表

這是一個粗略的例子:

<?php
  $truck_id = mysql_real_escape_string($_GET['truck_id']);



 $sql_PK = "SELECT * FROM table1 WHERE id = '{$truck_id}'";
 $res_PK = mysql_query($sql_PK);
 $row_PK = mysql_fetch_assoc($res_PK);

 $truck_plate = $row_PK['plate'];



$truck_plate = mysql_real_escape_string($truck_plate);



$sql = "SELECT table2.plate, table2.destination, table2.route, table3.plate, table3.diesel_price, table3.num_of_liters FROM table2, table3 WHERE table2.plate = table3.plate AND table2.plate = '{$truck_plate}'";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($res);


    // this will give you the details from the following

        //TABLE2
        // plate
        // destination
        // route

        //TABLE3
        // plate
        // diesel_price
        // num_of_liters


?>

有幾件重要的事情要記住。 首先是養成在數據庫中不使用空格命名字段的習慣,而是使用_。 因此,柴油價格為柴油價格,等等。其次,是確保您正在使用mysql_real_escape_string保護自己免受任何注入,如我在此處所示

因此,當有人單擊truckdetails.php?plate = mrtchi時,它將根據車牌號查詢數據庫:mrtchi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM