2015-02-11 80 views
0

我有一個數據庫表,用於存儲城市的航班信息,包括Destination_ID,Destinatination_City,Airline,Leaving_From和Arriving。SQL打印出兩行?

我運行以下查詢:

$name = $_GET['name']; 

    $dbQuery = $db->prepare("SELECT * FROM DESTINATIONS 
       WHERE destination_City = '$name' "); 

       $dbQuery->execute(); 
       $airlines= array(); 
       while ($dbRow = $dbQuery->fetch(PDO::FETCH_ASSOC)){ 
       $Airlines[] = $dbRow['Airline']; } 


foreach($Airlines as $Airline) 
{ 
$dbQuery = $db->prepare("SELECT * FROM DESTINATIONS 
WHERE Airline = '$Airline' AND Destination_City = '$name' "); 
$dbQuery->execute(); 

while ($dbRow = $dbQuery->fetch(PDO::FETCH_ASSOC)){ 
$Arriving = $dbRow ['Arriving']; 
$Leaving_From = $dbRow ['Leaving_From'] ; } 

echo "$Leaving_From to $Arriving" ; 
} 

此返回兩個結果與除了到達的列是不同的值相同。但是,在打印時,打印第二行兩次而不是打印兩行。

我不知道它爲什麼這樣做。誰能幫忙?

+5

你需要在'while'中放置'echo'。正如當前寫入的,變量被最後一次檢索到的行覆蓋 – kero 2015-02-11 12:42:42

+0

@kingkero剛剛嘗試過這種方式,現在它打印第1行兩次,第2行打印兩次? – OUDK 2015-02-11 12:47:32

+0

你有任何其他的代碼包含/調用張貼的行嗎? – kero 2015-02-11 12:48:52

回答

0

這是@OUDK參考:

$Airlines = array('Flyr'); 
$Airlines = array_unique($Airlines); 
$name = 'London'; 



foreach($Airlines as $Airline) 
{ 

    $dbQuery = $db->prepare("SELECT * FROM DESTINATIONS 
WHERE Airline = '$Airline' AND Destination_City = '$name' "); 

$dbQuery->execute(); 

while ($dbRow = $dbQuery->fetch(PDO::FETCH_ASSOC)){ 
    $Arriving = $dbRow ['Arriving']; 
    $Leaving_From = $dbRow ['Leaving_From']; 

    echo "$Leaving_From to $Arriving" . '<br>'; 
} 


} 

DB我​​只有3個例子:

+---------+------------------+--------------+----------+ 
| Airline | Destination_City | Leaving_From | Arriving | 
+---------+------------------+--------------+----------+ 
| Flyr | London   | Paris  | London | 
| Flyr | London   | Rome   | London | 
| Flyr | London   | Madrid  | London | 
+---------+------------------+--------------+----------+ 

我在倫敦的目的地和到達,是在這部分有點困惑。

輸出:

Paris to London 
Rome to London 
Madrid to London 

編輯----------------

我想我看到與上次編輯的問題,您使用由您的代碼得到航空公司的數組意味着,如果航空公司在結果一次也將是陣列中的更多,你可以添加array_unique上面一樣,但更好的方法是如下:

$dbQuery = $db->prepare("SELECT DISTINCT Airline FROM DESTINATIONS 
       WHERE destination_City = '$name' "); 

       $dbQuery->execute(); 
       $airlines= array(); 
       while ($dbRow = $dbQuery->fetch(PDO::FETCH_ASSOC)){ 
       $Airlines[] = $dbRow['Airline']; } 
0

dbQuery提取每次迭代都會得到一個結果集,因此您需要將回顯代碼放在while循環中,以便每次迭代都打印結果。相應地修改您的代碼以獲得所需結果