简体   繁体   English

PHP - MySQL:从表中获取两个日期之间的日期行

[英]PHP - MySQL: Get rows from table where date between two dates

I've got a problem with mysql getting the rows between two dates. 我有一个问题,mysql获取两个日期之间的行。

The column is res_birthday (VARCHAR) and the date looks like 30.11.1970 . 该列是res_birthday (VARCHAR) ,日期看起来像30.11.1970

Now I have to get customers whose birthdays are between 01.01. 现在我必须得到生日在01.01.之间的客户01.01. and 10.01. 10.01. , the year doesn't matter. ,这一年没关系。

I've tried many solutions with: 我尝试了很多解决方案:

STR_TO_DATE(`res_birthday`, '%d.%m')

but I cannot compare it to the start and end date. 但我无法将它与开始和结束日期进行比较。

Any idea how I can solve this? 知道如何解决这个问题吗?

Edit: 编辑:

Here is some code with the solutions mentioned below, but it does not work. 以下是一些代码与下面提到的解决方案,但它不起作用。

$query = mysql_query("SELECT * FROM `jtmpl2_chronoforms_data_test_reservierung` WHERE MONTH(STR_TO_DATE(`res_birthday`, '%d.%m.%y')) = 5 AND DAYOFMONTH(STR_TO_DATE(`res_birthday`, '%d.%m.%y')) = 10;");

     while($info = mysql_fetch_array( $query )) 



    function createCodeOrg($query){
     while($info = mysql_fetch_array( $query )) 
    { 
        $code = '<tr>
                            <td>'.$info['res_anrede'].'</td>
                        <td>'.ucfirst($info['res_vorname']).'</td>
                        <td>'.ucfirst($info['res_nachname']).'</td>
                        <td>'.ucfirst($info['res_strasse_hnr']).'</td>      
                        <td>'.$info['res_plz'].'</td>               
                        <td>'.ucfirst($info['res_ort']).'</td>
                        <td>'.$info['res_geburtstag'].'</td>    
                        <td><a href="mailto:'.$info['res_email'].'">'.$info['res_email'].'</a></td>                 

                      </tr>';

    echo $code;
    } 
}
select * from your_table
where MONTH(STR_TO_DATE(res_birthday, '%d.%m.%Y')) = 1
and DAYOFMONTH(STR_TO_DATE(res_birthday, '%d.%m.%Y')) between 1 and 10

SQLFiddle demo SQLFiddle演示

Your problem is you're storing dates as varchars. 您的问题是您将日期存储为varchars。 This removes the ability of the DB to what it could automatically if you'd been using DATE or DATETIME fields: 如果您使用DATEDATETIME字段,这将删除数据库能够自动执行的操作:

SELECT ...
FROM ...
WHERE res_birthday BETWEEN 'yyyy-mm-dd' AND 'yyyy-mm-dd'

Convert your fields now, and your problem essentially goes away. 现在转换你的字段,你的问题基本上消失了。

I believe this is what you are looking for: 我相信这就是你要找的东西:

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

Source: http://www.w3schools.com/sql/sql_between.asp 资料来源: http//www.w3schools.com/sql/sql_between.asp

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

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