我正在创建一个网络应用,如果用户点击名为“WEEK”的链接,该页面会显示该周提交的所有帖子。还可以选择查看本月提交的所有帖子。 posts表中有一个名为post_date的列,其中日期的格式为:YYYY-MM-DD。
我的问题:我不知道如何生成本周和月份提交的帖子。
我可以成功选择当前日期提交的帖子,如下所示:
$today = date("Y-m-d"); // This is the format of the DATE column named post_date in the posts table.
if($_GET['when'] == "today")
{
$when = $today;
}
else if ($_GET['when'] == "week")
{
$when = // I don't know what goes here if I want to generate posts submitted this week
}
else if ($_GET['when'] == "month")
{
$when = // I don't know what goes here if I want to generate posts submitted this month
}
// I have already connected to the database and selected the table.
$query = "SELECT * FROM posts WHERE post_date = '$when'";
$result = mysql_query($query);
// After this I Generate the Posts Using WHILE loop and mysql_fetch_array
如果URL中的$ _GET ['when']值是“今天”,则SCRIPT正常工作并生成“今天”提交的帖子。但我不知道如何选择当前周和当月。我已经完成了我的作业:我已经用Google搜索并搜索了StackOverflow的匹配问题,但是有一些问题,例如上周的数据,代码很直接,不适合我的情况。例如,可以选择使用WEEK($today,1)
选择第1周,第2周,第3周和第4周(我不知道它是否有效,但我想生成当前提交的帖子和月)。
提前致谢。
答案 0 :(得分:5)
有several MySQL functions为你做这样的事情
SELECT * FROM posts
WHERE
WEEK(post_date) = WEEK(CURDATE())
AND
MONTH(post_date) = MONTH(CURDATE())
答案 1 :(得分:2)
好吧,通过略微修改代码,您可以使用SQL实现WEEK和MONTH-Problem!
关于:MySQL-Documentation,这可能是您的解决方案:
SELECT *
FROM posts
WHERE YEARWEEK(post_date) = YEARWEEK(NOW())
第二个可能有点复杂:
SELECT *
FROM posts
WHERE YEAR(post_date) = YEAR(NOW())
AND MONTH(post_date) = MONTH(NOW())
我希望,我可以帮助你。
答案 2 :(得分:0)
这个怎么样?
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);