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.
$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
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)
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')
"
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))
]);