2017-08-27 39 views
2

我想獲得一個SQL查詢來運行顯示航空公司名稱列表的數組。然而,第一結果總是空從MySQL查詢結果的第一行不顯示它應該在哪裏

1.

  • 國泰

  • 英國航空公司

  • 新航

    等,當它應該顯示:

    1. 國泰

    2. 英航

    3. 新加坡航空公司

    我已經得到的代碼是:

    foreach ($flights as $b) { 
    $flightdata = explode(" ", $b); 
    $airline = $flightdata[2]; 
    
    
    $link = mysql_connect('xxx', 'xxx', 'xxx'); 
    if (!$link) { 
        die('Could not connect: ' . mysql_error()); 
    } 
    
    mysql_select_db("xxx") or die(mysql_error()); 
    
    $fetchairlinecode = "SELECT * FROM `airlines` WHERE `iatacode` = '$airline' LIMIT 0 , 30"; 
    
    $rs=mysql_query($fetchairlinecode); 
    
    while ($row = mysql_fetch_array($rs)){ 
    
    echo $row['airlinename']; 
    } 
    
    mysql_close($link); 
    
    } 
    

    任何人都可以看到我是什麼做錯了?

    +0

    您的數據庫中可能有一行沒有航空公司名稱?或者,你在'$ flightdata'中的iatacode沒有一行? –

    +0

    你有沒有試過直接在你的數據庫中使用SQL查詢? 你在哪裏打印數字?或者你的意思是有一個空行? –

    +0

    如果是這樣,你應該在你的數據庫中嘗試查詢,因爲它可能是一個arlinename =''someware。 –

    回答

    1

    第一件事情首先擺脫了非參數化查詢。

    $fetchairlinecode = 
    "SELECT * FROM `airlines` WHERE `iatacode` = '$airline' LIMIT 0 , 30"; 
    

    成爲

    $fetchairlinecode = 
    "SELECT airlinename FROM `airlines` WHERE `iatacode` = ? LIMIT 30";"; 
    

    use mysqliPDO

    $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');  
    if ($mysqli->connect_error) { 
        die('Connect Error (' . $mysqli->connect_errno . ') ' 
          . $mysqli->connect_error); 
    } 
    
    foreach ($flights as $b) { 
        $flightdata = explode(" ", $b); 
        $airline = $flightdata[2]; 
        $fetchairlinecode = 
        "SELECT airlinename FROM `airlines` WHERE `iatacode` = ? LIMIT 30"; 
        $stmt = $mysqli->prepare($fetchairlinecode); 
        $stmt->bind_param("s", $airline); 
        $stmt->execute(); 
        $stmt->bind_result($airlinename); 
        while ($stmt->fetch()) { 
         echo $airlinename; 
        } 
    } 
    $mysqli->close(); 
    

    不要使用now long obsolete mysql library

    在foreach語句前只打開一次數據庫連接。

    而不是LIMIT 0 , 30你可以只寫LIMIT 30