To add a rank
column to your query in MySQL >= 8.0 you can use the RANK()
window function.
Updated
To convert the time
column seconds into HH:MM:SS
as a TIME
data-type, up to 838:59:59
, you would compare two points in time. You can accomplish this by using TIMEDIFF
to compare NOW()
with the time
column value added to the current time using NOW()
.
TIMEDIFF(NOW() + INTERVAL `time` SECOND, NOW()) AS `played`
MySQL 8.0+
To specify the ranking order from highest to lowest time
column value, you would use.
RANK() OVER(ORDER BY `time` DESC) AS `rank`
DB-Fiddle
<?php
// Select Time and Rank based on highest to lowest time
$SelectTime = $db->query('SELECT
`name`,
`steamid`,
`time`,
TIMEDIFF(NOW() + INTERVAL `time` SECOND, NOW()) AS `played`,
RANK() OVER(ORDER BY `time` DESC) AS `rank`
FROM `users`
ORDER BY `rank`'); //order lowest to highest rank 1-10
// Print Output
foreach ($SelectTime as $PrintTime) {
echo "<tr>
<td><b>" . $PrintTime['rank'] . "</b></td>
<td><b>" . $PrintTime['name'] . "</b></td>
<td><a href='https://steamcommunity.com/profiles/" . $PrintTime['steamid'] . "' target='_blank'>" . $PrintTime['steamid'] . "</a></td>
<td>" . $PrintTime['played'] . "</td>
</tr>";
}
?>
</tbody>
Result
| name | time | played | rank |
| ---- | ---- | -------- | ---- |
| D | 1000 | 00:16:40 | 1 |
| B | 600 | 00:10:00 | 2 |
| C | 300 | 00:05:00 | 3 |
| A | 10 | 00:00:10 | 4 |
MySQL < 8.0
Alternatively in MySQL < 8.0, you can use a user-defined variable to increment the rank.
DB-Fiddle
<?php
$db->exec('SET @rank = 0');
// Select Time
$SelectTime = $db->query('SELECT
`name`,
`steamid`,
`time`,
TIMEDIFF(NOW() + INTERVAL `time` SECOND, NOW()) AS `played`,
@rank := @rank + 1 AS `rank`
FROM `users`
ORDER BY `time` DESC');
// Print Output
foreach ($SelectTime as $PrintTime) {
echo "<tr>
<td><b>" . $PrintTime['rank'] . "</b></td>
<td><b>" . $PrintTime['name'] . "</b></td>
<td><a href='https://steamcommunity.com/profiles/" . $PrintTime['steamid'] . "' target='_blank'>" . $PrintTime['steamid'] . "</a></td>
<td>" . $PrintTime['played'] . "</td>
</tr>";
}
$db->exec('SET @rank = NULL');
?>
</tbody>