按数据库中的选定列排序

Ordering by a selected column from database

我有以下 table 是为了显示 win/loss 记录和排名。不过,我 运行 遇到了两个问题。

即:

1

2

3等

有人可以为我 运行 遇到的这些问题指出正确的方向吗?

  <h2>Division 1</h2>
            <table>
                <tr>
                    <th>Rank</th>
                    <th>Name</th>
                    <th>Wins</th>
                    <th>Losses</th>
                </tr>
<?php
try {
    //Prepare
    if ($stmt = $con->prepare("SELECT * FROM team_rankings WHERE `division`=1")) {

        $stmt->execute();
        $stmt->bind_result($ranking_id, $ranking_user_id, $ranking_firstname, $ranking_username, $ranking_division, $ranking_wins, $ranking_losses); 

        //var_dump($stmt);

        if (!$stmt) {
            throw new Exception($con->error);
        }

    $stmt->store_result();
        while ($row = $stmt->fetch()) {
?>

            <tr>
                <td>1</td>
                <td><?php echo $ranking_firstname; ?></td>
                <td><?php echo $ranking_wins; ?></td>
                <td><?php echo $ranking_losses; ?></td>
        </table>
<?php       
        }
        }   else {
            echo "<p>There aren't any players in division 1 yet.</p>";
            }
}
catch (Exception $e)
{
    echo "Error: " . $e->getMessage();
}
?>

你需要这样使用ORDER BY

这样做:

SELECT * FROM team_rankings WHERE `division`=1" ORDER BY Wins DESC, Losses

更多:link

对于第一个问题,您 </table> 需要退出 php while 循环。还有一个计数器,您可以增加它并显示订单。

$count = 0;
while ($row = $stmt->fetch()) {
?>
    <tr>
        <td><php echo $count; $count++; ?></td>
        <td><?php echo $ranking_firstname; ?></td>
        <td><?php echo $ranking_wins; ?></td>
        <td><?php echo $ranking_losses; ?></td>
    </tr>      
<?php } ?>

</table>

有更好的吗?使用 foreach

编号问题可以这样解决:

$i = 1;
while ($row = $stmt->fetch()) {
    ?>
        <tr>
            <td><?php echo $i ?></td>
            <td><?php echo $ranking_firstname; ?></td>
            <td><?php echo $ranking_wins; ?></td>
            <td><?php echo $ranking_losses; ?></td>
        </tr>
    <?php       
    $i++;
}

这会将变量 $i 设置为“1”(在循环外),将变量回显为 <td> 中的数字,并在循环之前递增变量 $i++已关闭。

哦,是的,不要在循环中关闭 <table>。 :)

您似乎想在查询中使用 ORDER BY clause。它可以直接按列或通过某种计算进行排序。例如,您可以这样做:

SELECT *
FROM team_rankings
WHERE division = 1
ORDER BY
    (wins - losses) DESC,
    wins DESC

这样 1-0 的排名将高于 6-6 但低于 2-1。这有多合适由您决定。