简体   繁体   中英

The query does not accept datetime format of PHP

I am trying to run a query which searches users according to date range. This is the code:

$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";

The above query returns all the values regardless of the date range provide. But when I manually assign the date to variable '$to_date' than it gives the perfect result.

When I write $to_date = "2016-1-30"; and than fire the query than it gives desired result.

So is it something that the mysql query don't accepts the DateTime format and accepts only dates in the format of string?

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";

See the result and run the same in your database, you'll see the error then. This line will show you the query. Run it over to your database directly and it will give show you the error.

Try this

$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";

I believe the new DateTime won't work with the sql query. Try using it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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