简体   繁体   中英

How to select records between two dates using only month and year in PHP and MySQL?

So I have this code:

$date_from = "2017-04-01";
$date_to = "2017-05-01"

$stmt = $this->pdo->prepare("SELECT * FROM records where created_at BETWEEN :start_date AND :end_date");

$stmt->execute([':start_date' => $date_from, ':end_date' => $date_to]);

My created_at is a timestamp field.

My problem here is that though it works, I only need to select between months and year only in the created_at field because in my code, the date is also included in selecting data. I only want "2017-04" - "2017-5" records for example so that even if a record like "2017-05-31" is still under "2017-5" . What am I missing here?

Let's say I have a record where the created_at value is "2017-05-01" . It will not be selected because it's not between the given dates that's why I need to fix my code to only use months and years even if the dates given are with date.

Any help would be much appreciated.

format your datetime.

You can use a string comparison.

DATE_FORMAT('2017-04-01','%Y%m') return date: 201704 .

so your where clause should be

"created_at DATE_FORMAT(created_at,'%Y%m') >= DATE_FORMAT($date_from,'%Y%m') and DATE_FORMAT(created_at,'%Y%m') <= DATE_FORMAT($date_to,'%Y%m') "

Convert your Dates to timestamp in php or even mysql

PHP:
$date_from_timestamp = strtotime($date_from);
$date_from_timestamp = strtotime($date_to);


MySQL:
UNIX_TIMESTAMP($date_from)
UNIX_TIMESTAMP($date_to)
$date_from = "2017-04-01";
$date_to = date("Y-m-d",strtotime($date_from." +1 months"));

$stmt = $this->pdo->prepare("SELECT * FROM records where created_at BETWEEN :start_date AND :end_date");

$stmt->execute([':start_date' => strtotime($date_from), ':end_date' => strtotime($date_to]));

Try this. If you created_at is timestamp. Your searching criteria also need to be timestamp

To search within a month or year u may do like following.

 $date_from = "2017-04-01";
 $date_to = date("Y-m-d",strtotime($date_from." +1 months")); // to add one month from 2017-05-01

I assume you are ignoring the day of the input and requested to get both April and May records

$date_from = "2017-04-01";
$date_to = "2017-05-01";

$stmt = $this->pdo->prepare("SELECT * FROM records where created_at BETWEEN :start_date AND :end_date");

$stmt->execute([
    ':start_date' => date("Y-m-01 00:00:00",strtotime($date_from)), 
    ':end_date' => date("Y-m-31 23:59:59",strtotime($date_to))
]);

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