-1

I am trying to display "{number} {unit-of-time} ago" in my chat. However, when I'm expecting something like "2 minutes ago", I see "45 years" instead.

Nobody has an answer?

Here is the script:

<?php
$con = mysql_connect("localhost", "user", "pword");
mysql_select_db('chat', $con);
$result1 = mysql_query("SELECT * FROM logs ORDER BY id ASC");

$tm = mysql_query("SELECT timestamp FROM logs ORDER BY id ASC");

function _ago($tm, $rcs = 0)
{
    $cur_tm = time();
    $dif = $cur_tm - $tm;
    $pds = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
    $lngh = array(1, 60, 3600, 86400, 604800, 2630880, 31570560);
    for ($v = sizeof($lngh) - 1; ($v >= 0) && (($no = $dif / $lngh[$v]) <= 1); $v--) ;
    if ($v < 0) $v = 0;
    $_tm = $cur_tm - ($dif % $lngh[$v]);

    $no = floor($no);
    if ($no <> 1) $pds[$v] .= 's';
    $x = sprintf("%d %s ", $no, $pds[$v]);
    if (($rcs == 1) && ($v >= 1) && (($cur_tm - $_tm) > 0)) $x .= time_ago($_tm);
    return $x;
}

$timeagochat = _ago($tm, $rcs = 0);

while ($extract = mysql_fetch_array($result1)) {
    echo "<p class='show_message'><span class='uname'>" . $extract['username'] . "</span> <span class='time'>" . $timeagochat . " </span><br><span class='msg'>" . $extract['msg'] . "</span></p><br>";
}

?>

What can I do to let this function work?

Intera
  • 33
  • 1
  • 7

1 Answers1

0
  1. You have to fetch the date:

    $tm = mysql_query("SELECT timestamp AS t FROM logs ORDER by id ASC")->fetch_assoc()['t']; //obviously, check the size before you fetch

  2. You probably want to use strtotime() so for instance:

    $dif = $cur_tm-strtotime($tm);

  3. The $dif will be in milliseconds.

  4. What are you doing with the loops and the arrays? Too confusing.

5. WHY DO PEOPLE KEEP USING mysql_!!!

Community
  • 1
  • 1
Shahar
  • 1,687
  • 2
  • 12
  • 18