简体   繁体   中英

PHP and MYSQL Find Records Based on Date

I have been trying to pull records based on a specified date. In the DB I have a column where I store unix timestamps. The user has the option to select records based on a date. The user inputs: 08/08/2016 (for example)

How would I write my SQL statement to handle this?

$query .= "`".$o."` = '".date("Y-m-d",strtotime($v))."' AND ";

Here we see the line where part of the SQL statement is built, because more than one column could be targeted by the user during their search request.

Somehow I need to be able to turn $o (which is a column storing unix timestamps) into the Ymd format for comparison, as shown above and make this work in an SQL statement.

Any help would be appreciated.

EDIT

Here is what worked for me:

$query .= " ".$o." >= '".strtotime($v)."' AND ".$o." < '".(strtotime($v)+(24*60*60))."' AND ";

You can do something like:

"WHERE DATE(`$o`) = '".date("Y-m-d",strtotime($v))."'"

However this won't use indexes, so if you have a large table it will be slower. If you want to be able to use indexes you can do:

"WHERE `$o` >= ".date("Y-m-d",strtotime($v))."
  AND `$o` < ".date("Y-m-d",strtotime($v))." + INTERVAL 1 DAY"

You can also try this approach and use UNIX_TIMESTAMP on MySQL.

$v = '2016-08-04';
$query .= "'".$o."' = UNIX_TIMESTAMP('$v') AND ";

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