Php MySQL查询结果的第一行未显示在应该显示的位置
我试图通过一个显示航空公司名称列表的数组运行SQL查询。但是,第一个结果总是空的 一,Php MySQL查询结果的第一行未显示在应该显示的位置,php,mysql,sql,foreach,Php,Mysql,Sql,Foreach,我试图通过一个显示航空公司名称列表的数组运行SQL查询。但是,第一个结果总是空的 一, 国泰航空 英国航空公司 新加坡航空公司 等等,当它应该显示: 国泰航空 英国航空公司 新加坡航空公司 我得到的代码是: foreach ($flights as $b) { $flightdata = explode(" ", $b); $airline = $flightdata[2]; $link = mysql_connect('xxx', 'xxx', 'xxx'); if (!$link) {
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);
}
有人能看出我做错了什么吗?首先要处理的是非参数化查询
$fetchairlinecode =
"SELECT * FROM `airlines` WHERE `iatacode` = '$airline' LIMIT 0 , 30";
变成
$fetchairlinecode =
"SELECT airlinename FROM `airlines` WHERE `iatacode` = ? LIMIT 30";";
和或:
不要使用。
在foreach语句之前只打开数据库连接一次
您可以只写
限制30
而不是在数据库中可能有一行没有航空公司名称?或者您在$flightdata
中的iatacode没有一行?您是否尝试过直接在数据库中使用sql查询?你在哪里打印号码?或者您的意思是有一个空行?如果是,您应该在数据库中尝试该查询,因为它可能是arlinename=''someware。我不认为它是一个空行,因为即使我更改航空公司名称的顺序,它仍然会将第一个名称移动到第二个位置。我的代码显示了所有正确的结果,但它们只是一个位置!在foreach循环中使用mysql\u connect有什么原因吗?
$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();