0

I would like to check how many users are online on a certain moment on a single query. The thing is I have the time kept as DATETIME (in the online field) and I would like to compare it with time(). Here is the code:

$online_margin = 10; //in minutes;

$online_margin = $online_margin*60;
$difference = time() - $online_margin;

$query = "SELECT id FROM users WHERE online > $difference";

I've tried using convert() and cast but failed, so I'd appreciate some help on why...

1
  • $query = "SELECT id FROM users WHERE UNIX_TIMESTAMP(online) > $difference"; Commented Mar 24, 2014 at 10:36

2 Answers 2

2

You need to convert it to Y-m-d h:i:s format before comparing it to db field,

$online_margin = 10; //in minutes;

$online_margin = $online_margin*60;
$difference = time() - $online_margin;
$difference  = date("Y-m-d h:i:s",$difference); //Convert seconds to Y-m-d h:i:s format
$query = "SELECT id FROM users WHERE online > $difference";

Alternative: You can convert your column online to unix_time for comparing,

$query = "SELECT id FROM users WHERE UNIX_TIMESTAMP(online) > $difference";
Sign up to request clarification or add additional context in comments.

Comments

1

This is less efficient than the answer below, but it should work.

$query = "SELECT id FROM users WHERE UNIX_TIMESTAMP(online) > $difference"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.