PHP PDO - 如何从三个表中输出结果

时间:2013-02-21 11:41:55

标签: php database pdo

我有一个汽车预订系统数据库,我正在建设中。我有3张桌子:

car_table:

ID     | car_make | car_name
1      | Ford     | Focus
2      | BMW      | Z3
3      | Audi     | A5

booking_table:

booking_ID  | booking_time | total_cost | etc..
125674      | 2013-02-02   | 91.55     
887463      | 2013-01-19   | 52.00     
209930      | 2013-01-11   | 23.99  

reservation_table:

ID     | booking_ID | car_ID
1      | 125674     | 2
2      | 887463     | 2
3      | 209930     | 1

所以reservation_table将汽车与预订联系起来。现在我想在用户的表中输出以下结果:

booking_ID | booking_time | total_cost | car_ID | car_make | car_model 

我如何输出这个结果,到目前为止,我几乎有效:

$query = " 
SELECT 
    booking_ID, 
    total_cost, 
    booking_time, 
    customer_ID,
    car_ID
FROM 
    bookings_table as bb,
    reservation_table as br 
WHERE 
    bb.booking_ID = br.booking_ID AND
    payment_success=true   
ORDER BY 
    booking_ID desc 
LIMIT 
    10
";

try { 
    $stmt = DB::get()->prepare($query); 
    $stmt->execute(); 

    $rows = $stmt->fetchAll();
}  
catch(PDOException $ex) { 
    // Failed 
} 

foreach($rows as $row):
    <td>'.$row['booking_ID'].'</td>
    etc...
endforeach;

显示如下:

booking_ID | booking_time | total_cost | car_ID | car_make | car_model 
125674     | 2013-02-02   | 91.55      | 2      |          |  

所以我可以从reservation_table获取car_ID,但我不知道如何通过从reservation_table中取出car_ID来取出car_make / model。

0 个答案:

没有答案