我试图让SQL查询在一个数组中运行,该数组显示一个航空公司名称列表。但是,第一个结果始终是空的。
1.
新加坡航空公司
等等,当它应该显示:
我得到的密码是:
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);
}有人能看出我做错了什么吗?
发布于 2017-08-27 12:29:25
首先要处理的是非参数化查询。
$fetchairlinecode =
"SELECT * FROM `airlines` WHERE `iatacode` = '$airline' LIMIT 0 , 30";变成了
$fetchairlinecode =
"SELECT airlinename FROM `airlines` WHERE `iatacode` = ? LIMIT 30";";以及使用mysqli或PDO
$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();现在已长期过时的mysql库. 不使用
在foreach语句之前只打开一次数据库连接。
而不是LIMIT 0 , 30,您可以只编写LIMIT 30。
https://stackoverflow.com/questions/45904505
复制相似问题