简体   繁体   中英

Filter date order_date on its date range sql problem

$sql ="SELECT * FROM orders WHERE order_date >= '$fromdate' AND order_date <= '$todate'";

As you can see in the query above, it indicates the required from-date to to-date. Just a typical filtering of table.

在此处输入图片说明

As you can see.

From date value is 10/29/2018 and echo 2018-10-29.

TO date value is 10/30/2018 and echo 2018-10-30. because I formated my input date that way.

so the problem is that. I have these values from database :

2018-10-30 01:21:29pm

2018-10-29 01:21:29pm

so as you see it indicates time on it. So i want to scan all of these values even I have only date in input date.

Use the Date() function In Mysql

$sql ="SELECT * FROM orders WHERE Date(order_date) >= '$fromdate' AND Date(order_date) <= '$todate'";

Which will remove the time when comparing. There is also Year , Day , Month etc... The advantage of using a DateTime field over VarChar

AS a bonus an easy way to convert your date styles is like this

$date = (new DateTime('10/29/2018'))->format('Y-m-d');

Notice the (new DateTime) brackets, then you don't waste a local variable on it. I forget what version of PHP they added those in like 5.5 I think, anyway it should work in anything "current"

Last thing is you should look at prepared statements, instead of concatenating variables from the end user. Otherwise you will git smacked with the SQLInjection stick. For this query if you use something like Date Time to format the dates it will probably take care of most of that, but it's not the proper way to secure your SQL.

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