PHP返回的结果比mysql少

时间:2015-04-02 00:43:38

标签: php mysql mysqli

我有一个mysql查询,当我在mysql控制台中运行时返回4个结果,这正是我需要的,但是当我在PHP中尝试它时,我只得到2个结果。我的PHP有什么问题吗?我已经将查询回显到一个字符串,粘贴到控制台中,它也给了我我需要的东西。当我回显返回的行数时,它是2。

<?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";

$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>";

2 个答案:

答案 0 :(得分:0)

从自联接返回列时,请勿使用SELECT *ab中的列都相同,但您需要为它们指定不同的名称。所以使用类似的东西:

SELECT a.source AS start, 
       a.flightno AS flight1, 
       a.destination AS connection, 
       b.flightno AS flight2, 
       b.destination AS destination

然后在显示表格的代码中,执行:

while ($row = $result->fetch_assoc()) {
    foreach ($row as $col) {
        echo "<td>" . utf8_encode($col) . "</td>";
    }
}

您还需要更改显示列标题的代码,以使用与您选择的这些列对应的标题,而不是从SHOW COLUMNS获取标题(因为这样只会得到一组列名)。

答案 1 :(得分:-1)

您需要在包含空格的字段名称后面打勾。你需要像这样更改这些行:

AND `{$source}` = a.Source
AND `{$destination}` = b.Destination";