【问题标题】:How to get results given a starting and ending date from MySql?如何从 MySql 获取开始和结束日期的结果?
【发布时间】:2015-10-02 17:33:59
【问题描述】:

我的日历背面有以下代码:

// I get this from ajax (start month + end of the month)
$post_date_start = $_POST['date_start']; // start month (always), ie: 2015-09-01
$post_date_ending = $_POST['date_ending']; // end month (always), ie: 2015-09-31

// If I get an event which its duration its between $post_date_start and $post_date ending it works properly as you can see:
SELECT * FROM calendar WHERE start_date >= '$post_date_start' AND ending_date <= '$post_date_ending' 

问题:它实际上正确地返回了这些范围内的结果。但是如果start_dateending_date不在这个范围内,它不会返回任何东西。

例如,从 2015 年 7 月 9 日开始到 2015 年 8 月 12 日结束的活动。它应该在 9 月、10 月、11 月和 12 月展示......)。问题是......拥有这两个参数,我该如何在每个月/年显示事件?谢谢!

【问题讨论】:

    标签: php mysql calendar fullcalendar


    【解决方案1】:

    您正在将日期列与字符串文字进行比较,从而强制数据库将一个隐式转换为另一个。显然,日期被转换为字符串,并且按字典顺序进行比较。相反,您应该将字符串显式转换为日期,以便通过日期值进行比较:

    SELECT *
    FROM   calendar 
    WHERE  start_date  >= STR_TO_DATE('$post_date_start', '%Y-%m-%d') AND  
           ending_date <= STR_TO_DATE('$post_date_ending', '%Y-%m-%d')
    

    强制性评论:
    在 SQL 语句中使用字符串替换是一个坏主意,这会使您的应用程序容易受到 SQL 注入攻击。您应该考虑改用prepared statement

    【讨论】:

    • 嗨@Mureinik,我刚刚试过这个,但它不能正常工作。它的工作方式与我发布的完全相同。例如,如果 $post_date_start 是“2015-10-01”并且 $post_date_ending 是“2015-10-31”,我创建了一个 date_start = “2015-10-12”和 date_ending “2015-12- 12" 它不会显示任何内容,因为它只显示 10 月日期范围内的事件......请帮忙?谢谢!
    猜你喜欢
    • 2021-05-19
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多