【问题标题】:First row from MySQL query result not displayed where it should beMySQL 查询结果的第一行未显示在应在的位置
【发布时间】:2017-08-27 11:34:18
【问题描述】:

我试图让一个 SQL 查询通过一个显示航空公司名称列表的数组运行。但是第一个结果总是空的

1.

  1. 国泰航空

  2. 英国航空公司

新加坡航空公司

等,什么时候应该显示:

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

}

谁能看出我做错了什么?

【问题讨论】:

  • 您的数据库中可能有一行没有航空公司名称?或者您在 $flightdata 中的 iatacode 根本没有一行?
  • 你试过直接在你的数据库中使用sql查询吗?你在哪里打印数字?或者你的意思是有一个空行?
  • 如果是这样,你应该在你的数据库中尝试查询,因为它可能是一个 arlinename='' someware。
  • 我不认为这是一个空行,因为即使我更改了航空公司名称的顺序,它仍然会将第一个名称移到第二个位置。我的代码显示了所有正确的结果,但它们还差一个位置!
  • 在 foreach 循环中有 mysql_connect 有什么原因吗?

标签: php mysql sql foreach


【解决方案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 30,而不是LIMIT 0 , 30

【讨论】:

    猜你喜欢
    • 2020-08-30
    • 2011-10-26
    • 2014-02-02
    • 2013-01-31
    • 2013-11-05
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 2013-04-12
    相关资源
    最近更新 更多