简体   繁体   English

从两个日期之间的数据库获取数据

[英]Get data from a database that is between two dates

I am writing a system that will show data from a selected month. 我正在编写一个系统,将显示选定月份的数据。 The user can select the month they want to look at, this then creates a URL something like this .com/page.php?month=03 the page as you can guess will take the idea and then use it to get data from the database from that month. 用户可以选择要查看的月份,然后创建一个类似.com / page.php?month = 03的URL,您可能会猜到该页面会采用这个想法,然后使用它从数据库中获取数据。从那个月开始。

Now based on the month in the URL i am making to vars, $startdate $enddate start date based on this example is 2011-03-01, i then add 29 or 30 on to the days part of the date depending if the month has 31 or 30 days. 现在基于我在vars中创建的URL中的月份,基于此示例的$ startdate $ enddate开始日期为2011-03-01,然后我将29或30加上日期的天数,具体取决于该月份是否31或30天。 Okay so i do the dates like this: 好吧,我这样的日期:

$startdate = mktime(0,0,0,date("$month"),date("01"),date("2011"));
if( $month==04 || $month==06 || $month==9 || $month==11)
{
    $enddate = mktime(0,0,0,date("$month"),date("01")+29,date("2011"));
}
else
{
    $enddate = mktime(0,0,0,date("$month"),date("01")+30,date("2011"));
}

Now when i try to get the data from the database with these variables it doesn't seem to work, this is the query: 现在,当我尝试使用这些变量从数据库中获取数据时,它似乎不起作用,这是查询:

$getresults = mysql_query("SELECT * FROM table1 WHERE date BETWEEN $startdate AND $enddate ORDER BY date ASC");

The thing is if i change the vars to hard coded dates its works a treat... Anyone got any ideas? 关键是,如果我将vars更改为硬编码日期,那么它的工作就很划算……有人有任何想法吗? i was thinking it had something to do with the way the day is formatted? 我以为这与格式化日期有关吗? in my database its "Ymd" and is also the same in the php. 在我的数据库中,其“ Ymd”与php中的相同。

thank for any help people im really stuck on this one. 感谢人们对我的真正帮助。

mktime produces dates as Unix timestamps (eg. '1317046059') but your table stored dates in a different format (eg. '2011-09-26'). mktime将日期生成为Unix时间戳(例如'1317046059'),但是您的表以其他格式(例如'2011-09-26')存储日期。 To make your queries work, you will need to convert your timestamps into the appropriate format: 为了使查询有效,您需要将时间戳转换为适当的格式:

$enddate = date( 'Y-m-d', mktime(0,0,0,date("$month"),date("01")+29,date("2011")) );

Update: 更新:

Based on your new comment that your dates are stored as timestamps in your database, you will need to format your dates in this manner: 基于将日期存储为时间戳的新注释,您将需要采用以下方式格式化日期:

$enddate = date( 'Y-m-d h:i:s', mktime(0,0,0,date("$month"),date("01")+29,date("2011")) );

You should use a couple var_dump statements in key places to evaluate you code. 您应该在关键位置使用几个var_dump语句来评估代码。 This way, you can know EXACTLY what your data looks like, including its format, then you can figure out how to format that date the way you need to. 这样,您可以确切地知道数据的样子,包括其格式,然后可以弄清楚如何以所需的方式格式化该日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM