从查询中订购结果的问题

时间:2019-04-21 12:10:14

标签: php mysql

我正在尝试在查询循环内订购第二个查询,但似乎不起作用...我真正想要实现的是按ID对行进行订购,但是在第二个查询中却没有工作。

代码如下:

<table>

<?php

function convertToHoursMins($time, $format = '%02d:%02d') {
    if ($time < 1) {
        return;
    }
    $hours = floor($time / 60);
    $minutes = ($time % 60);
    return sprintf($format, $hours, $minutes);
}

$servername = "xxxx";
$username = "xxxxx";
$password = "xxxx";
$dbname = "xxx";

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

if(!$_GET["steam"])
{
    $steam = $steamprofile['steamid'];
}
else
{
    $steam = intval($_GET["steam"]);
}

$sql = "SELECT * FROM `TotalVIPs`";

$conn->set_charset("utf8");
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {


        //echo " <tr><th>". $row["SteamID"]."</th><td></tr>";

        $sql2 = "SELECT * FROM `PlayedTime` WHERE `steamid` LIKE '". $row["SteamID"] ."' ORDER BY id ASC";

        $conn->set_charset("utf8");
        $result2 = $conn->query($sql2);

        if ($result2->num_rows > 0) {
            while($row2 = $result2->fetch_assoc()) {

                $time = $row2["AllTotal"];
                $convtime = convertToHoursMins($time, '%d ore %d min');

                $steamprof = "<a href='profile.php?steam=" . $row2["communityid"]. "' class='btn btn-default btn-xs'>Profil</a>";
                echo " <tr><th>". $row2["id"]."</th><td>". $row2["playername"]."</td><td>". $row2["steamid"]."</td><td>". $convtime ."</td><td>". $row2["last_accountuse"]."</td><td>" . $steamprof . "</tr>";

            }
        }
    }
}
$conn->close();
?> 

</table>

我希望它按ID排序,但出于某种原因不这样做。

在这里,一张照片:http://prntscr.com/neuu74

1 个答案:

答案 0 :(得分:1)

由于您使用的是嵌套循环,因此总结果将由第一个查询的结果排序,并且仅在外部查询的每一行中按id排序。

相反,您应该使用将两个表连接起来的单个查询,然后可以按第二个表中的一列进行排序。

SELECT * 
FROM TotalVIPs AS v 
JOIN PlayedTime AS p 
ON p.steamid = v.steamid 
ORDER by p.id