Converting Seconds to HH:MM:SS [duplicate]
I found a function to convert seconds to HH:MM:SS online, the function is this:
function sec2hms ($sec, $padHours = false) {
$hms = "";
$hours = intval(intval($sec) / 3600);
$hms .= ($padHours)
? str_pad($hours, 2, "0", STR_PAD_LEFT). ':'
: $hours. ':';
$minutes = intval(($sec / 60) % 60);
$hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ':';
$seconds = intval($sec % 60);
$hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
return $hms;
}
I know this works fine as if I do echo(sec2hms(3600));
it will return as 1:00:00
What I want to happen is to use that function to convert every single entry in the column timeran
and then display it in a HTML table with the columns 开发者_开发问答username
and score
, I am not sure how to do this so if someone could help me out then that'd be great. I am currently using the code below to display the table but that only shows time taken in seconds and I would like it to be in HH:MM:SS:
<tr>
<th>Rank</th>
<th>Username</th>
<th>Time Taken (s)</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<?php
$result = mysql_query("SELECT * FROM gamescores ORDER BY Time DESC");
if (mysql_num_rows($result)) {
for($rank=1; $row = mysql_fetch_assoc($result); $rank++) {
echo "<tr>
<td>{$rank}</td>
<td>{$row['username']}</td>
<td>{$row['timetaken']}</td>
<td>{$row['score']}</td>
If there is a better way of converting seconds to HH:MM:SS then that would be great too.
Use the MySQL SEC_TO_TIME function.
Example:
mysql> SELECT SEC_TO_TIME(2378);
-> '00:39:38'
So you can write your SQL query as:
SELECT username, score, SEC_TO_TIME(timeran) as timetaken FROM gamescores ORDER BY Time DESC
Your code then becomes:
<?php
$result = mysql_query("SELECT username, score, SEC_TO_TIME(timeran) as timetaken FROM gamescores ORDER BY Time DESC");
if (mysql_num_rows($result)) {
for($rank=1; $row = mysql_fetch_assoc($result); $rank++) {
echo "<tr>
<td>{$rank}</td>
<td>{$row['username']}</td>
<td>{$row['timetaken']}</td>
<td>{$row['score']}</td>
You need to wrap your output with the function. Put this code in the appropriate place.
echo "<td>". sec2hms($row['timetaken']) . "</td>";
精彩评论