Calculate Last Week, Last Month in Mysql

We need get datas from last week, last month, yesterday and today. We can do it easily in MySQL.

Getting Current Date

SELECT CURDATE();

Result : 2009-06-04

Getting Last Week Datas

SELECT DATE_ADD('2009-06-04', INTERVAL 7 DAY);

Getting Last Month Datas

SELECT DATE_ADD('2009-06-04', 1 MONTH);

Getting Last Year Datas

SELECT DATE_ADD('2009-06-04', INTERVAL 1 YEAR);

And Php example for this calculations, getting last month orders

mysql_query("SELECT * FROM orders WHERE DATE_SUB(CURDATE(),INTERVAL 1 month) <= order_date")); 

For more information of Date and time functions :
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

Share and Enjoy:
  • StumbleUpon
  • Digg
  • TwitThis
  • FriendFeed
  • del.icio.us
  • MySpace
  • Technorati
  • Facebook
  • Google Bookmarks
  • Live

Enjoy this article?

Consider subscribing to our RSS feed!

Share us Facebook, FriendFeed, Digg

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

2 Comments

  1. sumon
    16:53 on August 14th, 2011

    down vote

    hi every one i need help i have a sql $getmonth = $_GET['month'];

    $SQL ="SELECT * FROM news Where MONTH(postdate) = $getmonth"; $execute = mysql_query($SQL) or die(mysql_error());

    here $getmonth=Aug-2011

    is not not able to get data how can i get the result like this way

  2. Hasan Yaşar
    21:56 on August 14th, 2011

    Easy solution;
    $startdate = $month.\”-01 00:00:00\”;
    $enddate = $month.\”-31 23:59:59\”;
    $query = \”Select * from news where postdate>=$startdate AND postdate <=$enddate";

Sorry, the comment form is closed at this time.

Oyun