我正在尝试运行一个根据日期范围搜索用户的查询。 这是代码:
$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格式并仅接受字符串格式的日期吗?
答案 0 :(得分:0)
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";
查看结果并在数据库中运行相同的内容,然后您将看到错误。此行将显示查询。直接将其运行到您的数据库,它会显示错误。
答案 1 :(得分:0)
试试这个
$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";
答案 2 :(得分:-2)
我相信新的DateTime不能使用sql查询。尝试使用它:
$to_date = date( "Y-m-d" );