Php 为什么日期变量之间的mysql查询不返回范围

Php 为什么日期变量之间的mysql查询不返回范围,php,date,range,Php,Date,Range,前言:我试图找到一个答案,虽然在一些回答的问题中有一些相似之处,但没有匹配 我试图生成3个月的报告,但只有当前日期返回值 <?php // Db connect include_once ('db.php'); global $con2; // 3 month reports $date_from = date("d-m-Y", strtotime(" -3 months")); $date_to = date('d-m-Y'); // Count $get = "select *

前言:我试图找到一个答案,虽然在一些回答的问题中有一些相似之处,但没有匹配

我试图生成3个月的报告,但只有当前日期返回值

<?php
// Db connect
include_once ('db.php');
global $con2;

// 3 month reports
$date_from = date("d-m-Y", strtotime(" -3 months"));
$date_to = date('d-m-Y');

// Count 
$get = "select * from table1 where date between '$date_from' and '$date_to'";
$get_connect = mysqli_query($con2, $get);
$get_rows = mysqli_num_rows($get_connect);

// Display data
echo $get_rows;
?>

使用dd-mm-yyyy字符串作为日期将无法正确使用“between”

但转换为真实日期会:

select
* , str_to_date(`date`,'%d-%m-%Y') 
from (
    select '10-10-2017' as 'date' union all
    select '11-11-2017' as 'date' union all
    select '10-10-1989' as 'date' union all
    select '10-10-2020' as 'date' union all
    select '10-10-3017' as 'date'
    ) table1
where str_to_date(`date`,'%d-%m-%Y') between str_to_date('10-10-2017','%d-%m-%Y')  and str_to_date('11-11-2017','%d-%m-%Y') 
order by str_to_date(`date`,'%d-%m-%Y') 


    date        str_to_date(`date`,'%d-%m-%Y')
1   10-10-2017  10.10.2017 00:00:00
2   11-11-2017  11.11.2017 00:00:00


此外:SQL中实现“between”的方式是第一个值必须低于第二个值(即值的顺序至关重要)。这是因为“between”实际上只是
somevalue>=compare\u val\u low和somevalue的语法快捷方式。为什么不在数据库中使用
date
数据类型作为日期?如果更改代码并输入硬编码日期,查询是否正常工作?只是为了定位错误的位置。在比较字符串时,错误是假设
20-11-2017
大于
21-09-2017
,但我确实建议花时间和精力更改您的datatypes@GrumpyCrouton尽管我同意事先准备好的陈述是首选的方式(在处理未知数据(如用户输入等)时,必须这样做),上述脚本实际上不存在SQL注入的风险
就是函数,但是你会遇到更大的问题。我只是想区分一下。我明白了。例如,谢谢。我想用变量实现这一点的唯一方法是将日期的格式更改为YY-mm-dd
select
* , str_to_date(`date`,'%d-%m-%Y') 
from (
    select '10-10-2017' as 'date' union all
    select '11-11-2017' as 'date' union all
    select '10-10-1989' as 'date' union all
    select '10-10-2020' as 'date' union all
    select '10-10-3017' as 'date'
    ) table1
where str_to_date(`date`,'%d-%m-%Y') between str_to_date('10-10-2017','%d-%m-%Y')  and str_to_date('11-11-2017','%d-%m-%Y') 
order by str_to_date(`date`,'%d-%m-%Y') 


    date        str_to_date(`date`,'%d-%m-%Y')
1   10-10-2017  10.10.2017 00:00:00
2   11-11-2017  11.11.2017 00:00:00
between '29-08-2017' and '11-11-2017'