Friday, 2 March 2012

Collecting records of current date or from last x seconds From Mysql DataBase

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 can collect records added or updated in last X seconds by using this query.

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 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 which automatically adds new posts or replies. We can check this by stopping posted within a particular duration.

No comments:

Post a Comment