Collecting records of current date or from last x seconds
We will try to get all records inserted or updated today. We will use the date and time field which stores the date and time data of the records. While comparing we will use MySQL curdate() function which returns today's date. Here is the query.
SELECT * FROM `test_time2` WHERE tm2 = curdate()
Here our tm field stores date data only. If we are storing date and time both then we have to change the query by adding a greater than equal to comparison.
SELECT * FROM `test_time` WHERE tm >= curdate()
This way we can collect records of present date. We can use DATE_SUB() functions to get the records of last 7 days or 15 days or X days.
Getting all records of last 10 minutes or 5 seconds or last one hour.
We will be using unix_timestamp() which gives output in Seconds elapsed since 1st Jan 1970
Here is the query to collect records added or updated in last X seconds.
SELECT * FROM test_time2 WHERE ( unix_timestamp( ) - unix_timestamp( tm ) ) < 5
The above query will return all records updated within last five seconds. This can be changed to X ( any ) seconds.
You can modify the above query to return records of last one hour or any time multiples in seconds.
This is required in preventing spam postings ( in forums etc. ) which automatically adds new posts or replies. We can check this by stopping posted within a particular duration.
Be the first to post comment on this article :
| ▼ Date & Time functions in SQL|