get record by date range in CodeIgniter [duplicate] - php

This question already has answers here:
Select data between a date/time range
(8 answers)
Closed 1 year ago.
I want to search records between two dates in CodeIgniter I have tried many methods but not getting required result.
My Model
function search($date1 , $date2 ){
$this->db->where('date<',$date1);
$this->db->where('date >',$date2);
$result = $this->db->get();
return $result;
}
My controller
function getsearch(){
$date1 = $this->input->post('txtdate1'); // 02-06-2015
$date2 = $this->input->post('txtdate2'); // 19-06-2015
$data['result'] = $this->result_model->search($date1,$date2);
$this->load->view("search_view",$data);
}
Now I want all rows between 2 to 19 but I am getting nothing.
Note: date type in mysql is varchar

02-06-2015 is a really suboptimal way to store dates in SQL, because they don't collate sensibly. If you can switch to a DATE or DATETIME data type, you'll be able to do cool stuff like indexing on the date column. But that's not what you asked.
Also, I wonder if you have your inequalities wrong? What's the start and end of the range of dates you want to search?
To answer your specific question:
The DATE_FORMAT() MySQL function will convert your char dates to collatable dates. In particular,
DATE_FORMAT('02-06-2015', '%d-%m-%Y')
gets you a DATE object from your dates.
So this sort of php code will work
$this->db->where("DATE_FORMAT(date, '%d-%m-%Y') < ","DATE_FORMAT('$date1', '%d-%m-%Y')");
$this->db->where("DATE_FORMAT(date, '%d-%m-%Y') > ","DATE_FORMAT('$date2', '%d-%m-%Y'):);
If $date2 is '01-06-2015' and $date1 is '04-06-2015' this will give back the records that fall on the second and third days of June.
You may want this instead for a [$date1,$date2] range.
$this->db->where("DATE_FORMAT(date, '%d-%m-%Y') >= ","DATE_FORMAT('$date1', '%d-%m-%Y')");
$this->db->where("DATE_FORMAT(date, '%d-%m-%Y') < ","DATE_FORMAT('$date2', '%d-%m-%Y') + INTERVAL 1 DAY");
Notice your date column is wrapped up in a function. That defeats the use of any index to do the table search on dates. If your date column had a DATE datatype, this would work. If you had an index on date MySQL would use a highly efficient range scan.
$this->db->where("DATE_FORMAT(date, '%d-%m-%Y') >= ","'$date1'");
$this->db->where("DATE_FORMAT(date, '%d-%m-%Y') < ","'$date2' + INTERVAL 1 DAY");
In raw SQL this would come out to...
WHERE DATE_FORMAT(date, '%d-%m-%Y') >= '$date1'
AND DATE_FORMAT(date, '%d-%m-%Y') < '$date2' + INTERVAL 1 DAY

Related

MYSQL Select between start end date date format d-m-Y [duplicate]

This question already has answers here:
Select mysql query between date?
(4 answers)
Select data between a date/time range
(8 answers)
MySQL - select data from database between two dates
(8 answers)
mysql: get record count between two date-time
(4 answers)
How do I query between two dates using MySQL?
(12 answers)
Closed 5 years ago.
If i do this in MYSQL it works:
SELECT * FROM reservations
WHERE
reservationStartDate >= '2018-01-01'
AND
reservationEndDate <= '2018-02-16'
AND
reservationSpace = 'kantoor-1'
So i want to make a function like this:
public function checkReservations($startdate, $enddate, $workspace, $bind="") {
//SELECT * FROM reservations WHERE reservationStartDate >= '2018-01-19' AND reservationEndDate <= '2018-02-01' AND reservationSpace = 'kantoor-1';
// Date format = 2018-12-31
$sql = "
SELECT * FROM DATABASENAME.reservations
WHERE
reservationStartDate >= '".$startdate."'
AND
reservationEndDate <= '".$enddate."'
AND
reservationSpace = '".$workspace."'
"
;
$this->run($sql,$bind);
}
And in php i use:
$test2 = $db->checkReservations('2018-01-01', '2018-02-16', 'kantoor-1');
echo '<pre>'.print_r($test2,true).'</pre>';
It show's nothing... Im almost there btw i have change the format of the date to Y-m-d
You can use the STR_TO_DATE MySQL function:
SELECT * FROM reservations
WHERE reservationStartDate
BETWEEN STR_TO_DATE('22-01-2018', '%d-%m-%Y')
AND STR_TO_DATE('03-02-2018', '%d-%m-%Y')
BETWEEN and STR_TO_DATE
BETWEEN is the better form of reservationStartDate >= '22-01-2018' AND reservationStartDate <= '03-02-2018' (also in terms of speed) but it your case it works only with STR_TO_DATE converting the 'd-m-Y' string to a real date format to let MySQL to handle it.
DATE type field
The best thing you can do is to use a DATE type field to store a date, so you don't need STR_TO_DATE anymore.
Try this:
SELECT * FROM reservations WHERE reservationStartDate >= '22-01-2018'
AND reservationEndDate<= '03-02-2018'
if you need to select rows from a MySQL database table in a date range, you need to use a command like this:
SELECT * FROM table
WHERE date_column >= '2014-01-01' AND date_column <= '2015-01-01';
You can use STR_TO_DATE() to convert your strings to MySQL date values :
SELECT * FROM reservations
WHERE reservationStartDate BETWEEN STR_TO_DATE('22-01-2018', '%d-%m-%Y') AND STR_TO_DATE('03-02-2018', '%d-%m-%Y')
However, you would be wise to convert the column to the DATE data type instead of using strings.

How to query a table based on timestamp with date in dd-mm-yyyy format

I have a table containing a field "created_at" whose Data Type is timestamp. I donot want to change it to DATE.
Can i query this table to fetch all rows of a day in format dd-mm-yyyy.
Note:
One approach I tried is:
a) Take Date in yyyy-mm-dd concatenate with 00:00:00
b) Take next date in yyyy-mm-dd concatenate with 00:00:00
and use below query to get all records of that day:
SELECT *
FROM news
WHERE created>='2016-12-13 00:00:00'AND
created < '2016-12-14 00:00:00'
Is this a good solution to my problem. Any better approach for this problem.
You can use the MySQL cast() function.
SELECT
*
FROM news
WHERE CAST(created_at AS DATE) = '2016-12-13'
This will discard the time component of your timestamp and do the comparison on only the date.
Reference: http://dev.mysql.com/doc/refman/5.7/en/cast-functions.html
If you don't want to change column datatype then you can go with this code
$startDate = strtotime( '2016-12-13' ); // it will convert date to timestamp format.
$endDate = strtotime( '2016-12-15');
$query = "SELECT * FROM news WHERE created >= '$startDate' AND created < '$endDate'";

convert Unix Time stamp and sort data in mysql query

I am trying to query a small database by date, my date table data is stored in time 2014-02-04 . how can I convert that and check it against todays date.
This is what I have but I am getting a few errors
$q = 'SELECT count(*) as count FROM SHOW WHERE date('Y-m-d', strtotime
('SHOW_DATE') ='.$db->qstr(date()).' AND CONTACT='.$db->qstr($name);
if(!$rs = $db->execute($q)){
force_page('core', 'error&error_msg=MySQL Error: '.$db->ErrorMsg().'&menu=1');
exit;
} else {
$today_count = $rs->fields['count'];
$smarty->assign('today_count',$today_count);
}
Thanks a lot.
You can convert show_date to a date format using FROM_UNIXTIME function. And then compare the date part of it with your input date value.
Example:
SELECT count(*) as count FROM `SHOW`
WHERE date( from_unixtime( `SHOW_DATE` ) ) = ? AND CONTACT=?
Use prepared statement to bind input values to the place holders.
To find a row containing a DATE matching the current date, use CURDATE():
SELECT column FROM table WHERE col_date = CURDATE()

Select a substring (date) and convert it

I have a table with a column DateFrom (Varchar) that uses format YYYY-MM-DDTHH:MM:SS
to get the time for a specific date I use this sql:
SELECT SUBSTRING(DateFrom FROM 12 FOR 5) AS From FROM calendar WHERE SUBSTRING(DateFrom FROM 1 FOR 10) = "'.$date.'"
this gives me:
HH:MM
.$date
(from datepicker) has format DD.MM.YYYY
I'm creating a website that should let the user see times associated with a date
can I convert the string from my database before checking if it's equal to .$date?
Or would it be better to change format from datepicker to YYYY.MM.DD instead?
How about getting rid of the the substring stuff and using this instead?
SELECT TIME(DateFrom) AS `From`
FROM Calendar
WHERE DATE(DateFrom) = STR_TO_DATE($date,'%d.%m.%Y')
This will work because your DateFrom field happens to be stored in the standard string format of a DATETIME object.
From is in backticks because it's a reserved word.
You really should consider changing the data type of your DateFrom column to DATETIME, and then indexing that column. Then you can change your WHERE clause to this
WHERE DateFrom >= STR_TO_DATE($date,'%d.%m.%Y')
AND DateFrom < STR_TO_DATE($date,'%d.%m.%Y') + INTERVAL 1 DAY
and you will get a very great performance advantage.
This is how i finally solved it:
$date1 = 18.02.2014;
$date2 = 22.02.2014;
$a = explode('.',$date1);
$revdate1 = $a[2].'-'.$a[1].'-'.$a[0];
$newdate1 = str_replace(".","-",$revdate1);
$b = explode('.',$date2);
$revdate2 = $b[2].'-'.$b[1].'-'.$b[0];
$newdate2 = str_replace(".","-",$revdate2);
SELECT SUBSTRING(DateFrom FROM 1 FOR 10) AS Date,
SUBSTRING(DateFrom FROM 12 FOR 5) AS StartTime,
SUBSTRING(DateTo FROM 12 FOR 5) AS EndTime
FROM Calendar WHERE SUBSTRING(DateFrom FROM 1 FOR 10)
BETWEEN "'.$newdate1.'" AND "'.$newdate2.'"
I know DATETIME would be better but that was not an option here (not my database).
So this solution takes a date with format dd.mm.yyyy and reformats it to yyyy-mm-dd and checks it against the substring date from my table.
so the query prints all:
Date, StartTime, EndTime
between two dates

Getting any rows which were added before a certain date

Would this be possible? I've used this to insert the date into a field called "date":
$date=date("m/d/y");
$sql="INSERT INTO pool (date) VALUES('$date' )";
$result=mysql_query($sql);
I've used this statement to get the date a week ago:
$variable = date('d-m-y', strtotime('-1 week'));
So how would I SELECT any rows which were added last week?
Instead of storing your dates as m/d/y, you should store them as Y-m-d :
$date=date("Y-m-d");
$sql="INSERT INTO pool (date) VALUES('$date' )";
In the database, you dates will then look like 2011-04-09.
That format is much easier to work with : alphabetical comparisons will work.
Which means that searching for rows that are older than a certain date would become something like this :
$variable = date('Y-m-d', strtotime('-1 week'));
$query = "select * from pool where date < '$variable'";
Also note that instead of working with a date field which is a varchar (or an equivalent) in your database, you could use a DATE column -- which would allow to to work with date and time functions in MySQL.
If the date field is a proper date type you can do < or > in your sql query. For example -
SELECT * FROM table WHERE date > '$date'
If you want everything from 1 week ago to now you can do something like the above or
SELECT * FROM table WHERE date BETWEEN '$date' AND NOW()

Categories