简体   繁体   中英

How to create a date range query using Mysql timestamp?

just need a little help here I hope you can help me with my simple problem.

I have a table that consist of shops data. In my PHP page the user can register their shops. And in registration the day that the user registered his/her account will be save in the database table and will format as a TIMESTAMP .

I have no problem with that. In my backend page there is a form for advance searching method. In my form, there is a dropdown field and beside it there is a datepicker that will format as mm/dd/yyyy so I have a 2 datepicker for that which is from and to .

My problem is:

I formatted the datepicker result using the strtotime() function in PHP. And I have a query like this.

$query = "SELECT * FROM shops
          WHERE status = '".$status."'
          AND registered BETWEEN ('".$from." AND ".$to."')";

Sample output of query is:

 SELECT * FROM shops WHERE status = 'P' AND registered BETWEEN ('1388505600' AND '1391097600');

Now I have a timestamp result for $from and $to. How can I filter it in mysql?

Ok that's all. Thanks in advance.

You should actually format a proper YYYY-MM-DD string format in PHP.

There basically is rarely ever a reason to work with UNIX timestamps in MySQL.

So do something like this for each of your datepicker to/from values:

$to_datetime = DateTime::createFromFormat('m/d/Y|', $datepicker_to);
$to = $to_datetime->format('Y-m-d');
$from_datetime = DateTime::createFromFormat('m/d/Y|', $datepicker_from);
$from = $from_datetime->format('Y-m-d');

And then use them in your query:

$query = "SELECT * FROM shops
          WHERE status = '".$status."'
          AND registered BETWEEN ('".$from."' AND '".$to."')";

Note that I have used PHP DateTime class, which I would HIGHLY recommend as your go to tool for date manipulation in PHP (along with it's related classes like DateInterval , DatePeriod , DateTimeZone , etc.)

如果registered的列不在UNIX时间中,则需要除去时间戳周围的引号,并且需要使用FROM_UNIXTIME()。

我认为您需要使用FROM_UNIXTIME

$query = "SELECT * FROM shops WHERE status = '".$status."' AND registered BETWEEN FROM_UNIXTIME(".$from.") AND FROM_UNIXTIME(".$to.")";

PHP

// $t is the value you got from strtotime()
$FormattedDateTime = date('Y-m-d H:i:s', $t)

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