MySQL: Select data from a table where the date falls in the current Week and current Month

前端 未结 3 912
孤城傲影
孤城傲影 2021-01-24 19:34

I am creating a web app where if a user clicks on Link called \"WEEK\", the page shows up all the posts which were submitted in that week. There\'s also an option to view all th

相关标签:
3条回答
  • 2021-01-24 19:41

    Well, by slightly modifying your code, you could realize the WEEK- and MONTH-Problem using SQL!

    Regarding to: MySQL-Documentation, this might be the solution for you:

    SELECT *
    FROM   posts
    WHERE  YEARWEEK(post_date) = YEARWEEK(NOW())
    

    Second one may be a bit more complicated:

    SELECT *
    FROM   posts
    WHERE  YEAR(post_date) = YEAR(NOW())
    AND    MONTH(post_date) = MONTH(NOW())
    

    I hope, i could help you.

    0 讨论(0)
  • 2021-01-24 19:46

    There are several MySQL functions that do things like this for you

    SELECT * FROM posts
    WHERE
       WEEK(post_date) = WEEK(CURDATE())
       AND
       MONTH(post_date) = MONTH(CURDATE())
    
    0 讨论(0)
  • 2021-01-24 19:52

    What about this?

    if($_GET['when'] == "today") {
        $query = "SELECT * FROM posts WHERE DATE(post_date) = CURDATE()";
    } else if ($_GET['when'] == "week") {
        $query = "SELECT * FROM posts WHERE post_date >= DATE_SUB(NOW(), INTERVAL 1 WEEK)";
    } else if ($_GET['when'] == "month") {
        $query = "SELECT * FROM posts WHERE post_date >= DATE_SUB(NOW(), INTERVAL 1 MONTH)";
    }
    $result = mysql_query($query);
    
    0 讨论(0)
提交回复
热议问题