我设置了一个数据库表,用于存储城市中的航班信息,其中包含字段Destination_ID,Destinatination_City,Airline,Leaving_From和Arriving。
我运行以下查询:
$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" ;
}
这将返回两个具有相同值的结果,但到达的列不同。但是,在打印时,它会将第二行打印两次,而不是打印两行。
我不确定为什么会这样做。有人可以帮忙吗?
答案 0 :(得分: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']; }
答案 1 :(得分:0)
dbQuery在每次迭代时都会获取一个结果集,因此您需要将echo代码放在while循环中,以便在每次迭代时打印结果。相应地修改您的代码以获得所需的结果。