查询返回给定源和目的地的转机航班

时间:2015-04-01 23:04:11

标签: php mysql mysqli

所以我有一张名为" Flights"存储航班的来源和目的地。说你有A - > B和B - > C在表格中,您将来源作为' A'和目标作为' C',查询应返回这两个A - >之间的路径。 B,B - > C.我试过这个问题:

$result = $mysqli -> query(
        "SELECT *
        FROM Flights a
        JOIN Flights b
        ON a.Destination = b.Source
        AND '{$source}' = a.Source
        AND '{$destination}' = b.Destination");

作为旁注:我在PHP中使用mysqli。我在mysql控制台中完成了这个查询,它返回了我需要的一切。但是,如果我在示例表上用PHP运行此查询,我会给它返回B - >仅限C。我出错的任何想法?我认为这可能与PHP字符串格式有关。

<?php
if(isset($_POST['source'])){
$source = $_POST['source'];
}

if(isset($_POST['destination'])){
$destination = $_POST['destination'];
}

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Airport Tracking";
$table ="Flights";
$flag = 0;

// Create connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

if(isset($_POST['source']) && isset($_POST['destination'])){
$columns= $mysqli -> query("SHOW COLUMNS FROM $table");

$sql = "SELECT *
FROM Flights a
JOIN Flights b
ON a.Destination = b.Source
AND {$source} = a.Source
AND {$destination} = b.Destination";

echo "$sql";

$result = $mysqli -> query($sql);


if($result == FALSE){
echo "<br><b>Incorrect input</b>";
$flag = 1;
}
else if($result->num_rows == 0){
echo "<br><b>Returned no results</b>";
$flag = 1;
}

}

$array = array();
$i = 0;

if(isset($_POST['source']) && $flag == 0){
// Display results
echo "<table>";
echo "<thead><tr>";
while ($row = $columns -> fetch_array(MYSQLI_BOTH)) {
echo "<th>" .$row['Field']. "</th>";
$array[] = $row['Field'];
}
echo "</tr></thead>";

while ($row = $result -> fetch_array(MYSQLI_BOTH)) {
echo "<tr>";
while ($i < sizeof($array)) {
    echo "<td>" .utf8_encode($row[$array[$i]]). "</td>";
    $i++;
}
echo "</tr>";
$i = 0;
}
echo "</table>";
}



$mysqli->close();
?>

这是我的PHP代码。我道歉,因为我知道缩进是不正确的。

0 个答案:

没有答案