查询不接受PHP的日期时间格式


The query does not accept datetime format of PHP

我正在尝试运行一个根据日期范围搜索用户的查询。这是代码:

$to_date = trim($_POST['to_dates']);
$to_date = new DateTime($to_date);
$to_date = $to_date->format('Y-m-d'); // I have tried printing the value of this variable and it holds the exact date selected by the user like this: 2016-1-30
$SQL = "SELECT cust_id,cust_name,cust_mobile,cust_address,state_name,room_no,check_in,check_out,extra_bed 
        FROM cust_details,room_details,states 
        WHERE check_in between '2016-1-01' and '$to_date' AND cust_details.room_id=room_details.room_id AND cust_details.cust_state=states.state_id 
        GROUP BY cust_details.cust_id";

无论提供的日期范围如何,上述查询都会返回所有值。但是,当我手动将日期分配给变量"$to_date"时,它会给出完美的结果。

当我写$to_date = "2016-1-30";并触发查询时,它会给出所需的结果。

那么,mysql查询不接受DateTime格式,只接受字符串格式的日期,这是什么原因呢?

echo "SELECT cust_id,cust_name,cust_mobile,cust_address,state_name,room_no,check_in,check_out,extra_bed FROM cust_details,room_details,states WHERE check_in between '2016-1-01' and '$to_date' AND cust_details.room_id=room_details.room_id AND cust_details.cust_state=states.state_id GROUP BY cust_details.cust_id";

查看结果并在数据库中运行相同的程序,然后就会看到错误。此行将显示查询。直接将它运行到您的数据库中,它会向您显示错误。

试试这个

$to_date = $_POST['to_dates'];
$to_date = str_replace('/', '-', $to_date);  // Check format (optional code)
$to_date = date("Y-m-d",strtotime($to_date));
$SQL = "SELECT cust_id,cust_name,cust_mobile,cust_address,state_name,room_no,check_in,check_out,extra_bed 
        FROM cust_details,room_details,states 
        WHERE check_in between '2016-1-01' and '".$to_date."' AND cust_details.room_id=room_details.room_id AND cust_details.cust_state=states.state_id 
        GROUP BY cust_details.cust_id";

我认为新的DateTime无法与sql查询一起使用。试着这样使用:

$to_date = date( "Y-m-d" );