Wrong logic in If Statement?

Question!

$repeat_times = mysql_real_escape_string($repeat_times);

$result = mysql_query("SELECT `code`,`datetime` FROM `fc` ORDER by datetime desc LIMIT 25") or die(mysql_error());

$output .="";
$seconds = time() - strtotime($fetch_array["datetime"]);

if($seconds < 60)
  $interval = "$seconds seconds";
else
 if($seconds < 3600)
     $interval = floor($seconds / 60) . " minutes";
else
    if($seconds < 86400)
         $interval = floor($seconds / 3600) . " hours";
    else
         $interval = floor($seconds / 86400) . " days";

while ($fetch_array = mysql_fetch_array($result)) {

	$fetch_array["code"] = htmlentities($fetch_array["code"]);
	$output .= "<li><a href=\"http://www.***.com/code=" . htmlspecialchars(urlencode($fetch_array["code"])) . "\" target=\"_blank\">" . htmlspecialchars($fetch_array["code"]) . "</a> (" . $interval . ") ago.</li>";

}

$output .="";

return $output;

Why is this returning janice (14461 days) instead of janice (15 minutes ago)

The datetime function table has the DATETIME type in my table so it's returning a full string for the date.

By : Icemanind


Answers

My guess would be that the strtotime() is returning false.

Considering today is 14461 days from the unix epoch.

You could use the SQL statement to fetch UNIX_TIMESTAMP(datetime) as timestamp and take that math out of the php code.

Also - You are calculating $interval before fecthing an array. Try making that whole section of code into a function that takes a timestamp and returns the "interval"

function get_interval($time) {
  $diff = time() - $time;
  // .... calculate interval here
  return $interval
}
By : gnarf


The time calculation code should go inside the while loop, since you want to calculate the time on a per-record basis (that and it's referring to $fetch_array, which is only retrieved as part of the while loop)



This video can help you solving your question :)
By: admin