Creating a leaderboards, how would I go about displaying rank/position?

南楼画角 提交于 2019-12-04 18:22:09

I recommend reading up on PHP/MySQL.

HTML Header: Open your table, create your headers

<table>
    <tr>
        <td>Rank</td>
        <td>User</td>
        <td>Score</td>
    </tr>

PHP: Dynamically generate the rows for each user

    <?php

        $result = mysql_query("SELECT user, score FROM leaderboard ORDER BY score DESC");
        $rank = 1;

        if (mysql_num_rows($result)) {
            while ($row = mysql_fetch_assoc($result)) {
                echo "<td>{$rank}</td>
                      <td>{$row['user']}</td>
                      <td>{$row['score']}</td>";

                $rank++;
            }
        }
    ?>

HTML Footer: need to close the table

</table>

You can do the whole thing in SQL:

SET @row = 0;
SELECT
    @row := @row + 1 AS rank
    userName,
    score
FROM
    leaderboard
ORDER BY
    score DESC

You need to 1) get the score of the record you're trying to rank 2) count the number of records with a "better" score ("better" is dependent on your type of game. Basketball, higher scores are better. Golf, lower scores are better.)

So, something like

select records in order
for each record
    score = record.score
    rank = select count(*) + 1 from table where score_column is better than score
    display data
end for

The problem is that performing the count(*) on any significant amount of data is slow. But you can see that once you have the rank of the first TWO differing scores, you can determine the rank of the remaining rows in your code without a query. But remember: you probably need to account for ties.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!