Question

I'm trying to make a table of results including the timestamp for each entry from the database. However, I need the time to be displayed as "X seconds/minutes/hours ago".

I've tried the jQuery timeago plugin with zero success and am now wondering how to do this for each entry.

$result = mysql_query("SELECT * from realmfeed order by ID asc");

echo "<table class='display'>\n";

while($row = mysql_fetch_array($result))
{
    echo "<tr><td><b>".$row['ID']."</b></td>\n";
    echo "<td>".$row['eventType']."</td>\n";
    echo "<td>".$row['server']."</td>\n";
    echo "<td>".$row['realm']."</td>\n";
    echo "<td>".$row['name']."</td>\n";
    echo "<td>".$row['time']."</td>\n</tr>\n\n";
}


echo "</table>\n";

How is it possible to create a "time ago" function for each result?

Was it helpful?

Solution

$time = strtotime($row['time']);
$dbDate = new DateTime($time);
$currDate = new DateTime();
$interval = $currDate->diff($dbDate);
echo $interval->d." days ".$interval->h." hours";

please refer to DateInterval for available functions and fields

OTHER TIPS

I would get the time stamp from MYSQL then do the maths in php eg.

$result = mysql_query("SELECT ..., UNIX_TIMESTAMP(time) as time FROM realfeed ORDER BY ID ASC");


$row = mysql_fetch_array($result);
$then = $row['time'];
$now = time();

$diff = $now - $then; //Now you have the difference in seconds

There is a nice function here you could use the difference on although I have not checked it myself.....

http://itwigle.com/twig/PHP_Time_Ago_Function

The problem with using PHP to do the time difference calculations is you're assuming the MySQL and PHP servers are in the same time zones. Better to do the difference calculation in the SELECT:

SELECT TIMEDIFF(NOW(), `time`) AS ago FROM realmfeed ORDER BY ID ASC

This will return hh:mm:ss formatted time difference.

Or if you'd prefer just the number of seconds:

SELECT TIME_TO_SEC(TIMEDIFF(NOW(), `time`)) AS secondsAgo FROM realmfeed ORDER BY ID ASC

try this this may help

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="jquery.timeago.js"></script>
</head>

<body>
<?php 
$result = mysql_query("SELECT * from realmfeed order by ID asc");

echo "<table class='display'>\n";

while($row = mysql_fetch_array($result))
{
    echo "<tr><td><b>".$row['ID']."</b></td>\n";
    echo "<td>".$row['eventType']."</td>\n";
    echo "<td>".$row['server']."</td>\n";
    echo "<td>".$row['realm']."</td>\n";
    echo "<td>".$row['name']."</td>\n";
    echo "<td><abbr class=\"timeago\" title=\"".date("j F Y h:i:s A",$row['time'])."\"></abbr></td>\n</tr>\n\n";
}


echo "</table>\n";
?>

    <script>
    jQuery(document).ready(function($){
     $("abbr.timeago").timeago()

    });
    </script>

</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top