MYSQL date range query strange behaviour - php

i'm working on codeigniter and mysql db. I have run in to a issue where i need to show recent data as per date.
i have table name tbl_tournament where i'm going to fetch tournament data whose tournament_end_date >= $todays_date
My Query
$today = date("d/m/Y");
$this->db->select('*');
$this->db->from('tbl_tournament');
$this->db->where('is_deleted', FALSE);
$this->db->where('tournament_end_date_time >=', $today);
$this->db->order_by('tournament_start_date_time');
$query = $this->db->get();
return $query->result_array();
the output of this query is empty array
array();
When i manually change tournament_end_date_time = 01/04/2018 in database and query $this->db->where('tournament_end_date_time >=', '01/04/2017'); i get results. But when i change date in query as $this->db->where('tournament_end_date_time >=', '31/12/2017'); i get empty array.
In Mysql database i have used varchar as the data type tournament_end_date_time
Thank in Advance.

You store datetimes as strings (with VARCHAR type), hence they're compared as strings - character by character. For obvious reasons, '3' character is greater than '1'. That's why with filter set...
WHERE tournament_end_date_time >= '31/12/2017'
... you'll only get the results where corresponding values start from '31/12' - in other words, of December, 31 (of 2017 - or any year after it).
To solve the problem, you can use STR_TO_DATE() MySQL function to convert the existing column value to an actual date. Note that the param will be treated as a date literal as it follows 'YYYY-MM-DD' format:
WHERE STR_TO_DATE(tournament_end_date_time, '%d/%m/%Y') >= '2017-12-31'
... or, in PHP syntax, following CodeIgniter conventions:
$this->db->where(array(
"STR_TO_DATE(tournament_end_date_time, '%d/%m/%Y') >=" => date("Y-m-d")
));
A better choice is doing a single-time update operation on this column to convert all its values to DATE type at once.

Related

How to pass value from date range picker to SQL?

I faced two problems here:
(A) How do I pass the value of start date and end date from this http://www.daterangepicker.com/#example4 into query *select * from table_name where date between 'start date' and 'end date'*
(B) My data consists of date within 2018/04/11 to 2018/04/13,which means it also include these two dates. How to ensure the selected date range can be displayed in the query result?
first of all, sql stores them using different format (by default) so you will have to convert it, maybe by using strtotime() and date() combination to get the wanted SQL format.
then you can use BETWEEN WHERE clause to filter values like:
WHERE created_at BETWEEN 2018-04-11 AND 2018-04-13
First extract the dates via explode:
$dates = explode(" to ", $datesFromDatepicker);
Then create the start and end date:
$start= DateTime::createFromFormat('Y/m/d', $dates[0]);
$end= DateTime::createFromFormat('Y/m/d', $dates[1]);
In your query use:
$start->format("Y-m-d");
$end->format("Y-m-d");

Compare oracle date in query with PHP

I want to compare dates retrieved from oracle database in php. but i don't know how to convert month name like Sep to SEP. I don't know how to convert month in capital letters. I want to convert 2015-09-01 formate to 03-SEP-15.
//sDate: 2015-09-01 eDate: 2015-09-03
$date1=date('d-M-Y', strtotime($sDate));
$date2=date('d-M-Y', strtotime($eDate));
// CREATEDATE: 03-SEP-15 02.44.42.000000 PM
QUERY:
$stid = oci_parse($conn, "SELECT * FROM table1 WHERE CAST(CREATEDATE AS DATE) between '".$sDate."' AND '".$eDate."'");
ERROR:
Warning: oci_execute(): ORA-01861: literal does not match format string
In Oracle you can convert a string into a date using the to_date() function. And a date to a string using the to_char() function
Example
to_date('01-JAN-2015','DD-MON-YYYY')
will return a value of type date.
Now, in your query you must make sure that the values in your "between" statement are date values. The only way to ensure that is to make $sDate a atring value and use the to_date function.
Assuming that your date strings are in format 01-JAN-2015...
$stid = oci_parse($conn,
"SELECT *
FROM table1
WHERE CAST(CREATEDATE AS DATE)
between to_date('".$sDate."','DD-MON-YYYY')
AND to_date('".$eDate."','DD-MON-YYYY')");
See also the Oracle documentation on date formats.
http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm
So you have a date string like this: '2015-09-01' and you want to convert it to '01-09-2015' to be used in a query.
If you want to debug if the issue is in how you handle the date conversion in php try to do:
list($year,$month,$day)=explode('-',$date);
$months = ['','JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
$date = implode('-',$day,$months[$month],$year);
Then try to run the query. You don't need to take the string, convert it into a date (unix timestamp) and convert it back to a string if you just need to change the order of the elements in the date. You have to follow your approach if you want to manipulate your date adding or removing some time or stuffs like that.
If the query is still in error and you are sure that dates in your db are stored with that pattern than the issue is in the query syntax

SQL Query in php not working as required

I have a Database with column name DT, that has values:
1. 16-05-2015
2. 16-05-2015
3. 30-06-2015
4. 30-06-2015
Sql query in php that I am using is:
$sql = "Select * from logs WHERE (DT<= '$to') AND (DT>= '$from') ";
I have also used query:
$sql = "Select * from logs WHERE (DT BETWEEN '$to' AND '$from') ";
Both the queries are not functioning in the same way as required.
If $to=31-05-2015 and $ from = any date before 31st, the query displays the 30-06-2015 date as well, but it is not in the range.
When $to=30-05-2015, correct results are displayed but choosing any date after 30-05-2015 does not display the correct range, what could be the reason of it?
You have to change your date format to yyyy-mm-dd while saving it to the database and change it to the dd-mm-yyyy while displaying, and also change the datatype of the column to the datetime to make you query work
$newdate = date("d-m-Y", strtotime($yourdate));
apparently, DT is not configured as date in your DB.
And thus the values are ordered lexigoraphically, as strings.
(In lexigoraphical order: 30-... is before 31-..., no matter what ... might be)
You can either change your data to be saved as yyyy-mm-dd strings.
Or configure the column correctly as date

convert date data into mysql date format

I want to convert the data on which I have the format
$dateToday = date("d-m-Y");
so the value of $dateToday is 27-12-2012
Then I want to save it to the database with the mysql data type date. How to keep the value of 27-12-2012 it can be stored in the mysql database with the format 2012-12-27?
Help me please. Thank you
Yes, you can convert the date with strtotime();
$dateToday = date("d-m-Y");
$newDate = date("Y-m-d", strtotime($dateToday));
OUTPUT: 2012-12-27
And then you can store data to your database.
When you have to recover the date you can reverse this operation like this:
$dateFromDatabase = "2012-12-27";
$reverseDate = date("d-m-Y", strtotime($dateFromDatabase));
OUTPUT: 27-12-2012
(corrected "Y-m-d" to "d-m-Y" in 2nd date call)
this is how it works:
You have to store your data in the proper mysql format. It will allow you to make whatever ordering, aggregating, filtering and calculating your dates.
But when you need to display your data, you may convert it in whatever format you wish, using mysql DATE_FORMAT() function:
SELECT DATE_FORMAT(dt,'%d-%m-%Y') as dtf FROM TABLE
will give you dtf field formatted in your custom format
i'll show u how to do that.
To explain i create one table called testtable1 it contain only one column called
col1 of type DATE
Table creation query is given below
CREATE TABLE `testtable1` (
`col1` DATE NULL DEFAULT NULL
)
Following query will work as you need.
In the first line i declared a string variable. In the second line i converted that string to your required date format and inserted into table.
set #var1='27-12-2012';
insert into testtable1 values(STR_TO_DATE(#var1, '%d-%m-%Y'))
You could also try to use the mysql function for converting to a date from a string, i.e
STR_TO_TIME
.
The SQL query could be
INSERT INTO foo_table (foo_date)
VALUES (STR_TO_DATE('27-12-2012','%d,%m,%Y'))
If you want to store data in MYSQL table in this format, you need to declare the column as varchar.
Because the datetime store date in a different format like 'yyyy-mm-dd hh:mm:ss'
The output is wrong This cannot show the date from the database .This show 1970/01/01.....
$date=Date($year."/". $month."/". $day);
$date=Date("Y-m-d", strtotime($date));
echo $date;enter code here
Try this
$dateToday = date("d-m-Y");
$dateForMysql = date('Y-m-d', $dateToday));

Date search Sql Query

im storing the timestamp in mysql database in (INT) column, And i want to search the rows with between the dates. Anyone would please help what should be the Sql query to find the rows between two dates?
dates are entered like
FROM DATE = 15-10-2011
END DATE = 01-11-2011
It depends on what algorithm you use to convert the date strings to int values.
If the algoritm is mototonic, for example: If a day (say 15-10-2011) is converted to n (say 5037), then the next day (16-10-2011) is always converted to n+1 (so 5038 in this example.)
then you could just use:
WHERE IntField BETWEEN MySpecialConvertDateToIntFunction('15-10-2011')
AND MySpecialConvertDateToIntFunction('01-11-2011')
If your field stores different timsetamps as different integers (and the conversion is monotonic), you could change the above code slightly to:
WHERE IntField >= MySpecial...Function('15-10-2011')
AND IntField < MySpecial...Function('02-11-2011') --- notice the date+1
But it's usually better to use a field of the MySQL DATE type for storing dates. Unless you want to store dates before 1000 or after 9999 off course.
If you want to store timestamps, there's also a TIMESTAMP type. Read the
MySQL docs: DATETIME, DATE, and TIMESTAMP Types
You can use The BETWEEN operator, which selects a range of data between two values. The values can be numbers, text, or dates.
You can see there:
http://w3schools.com/sql/sql_between.asp
I would ask you to set data type as timestamp/datestamp & then
//php code
$date1=date ('Y-m-d' , strtotime ( "15-10-2011") );
$date2=date ('Y-m-d' , strtotime ( "01-11-2011") );
//sql code
SELECT * FROM tbl_mytbl WHERE DATE(attr_date) <'$date2' AND DATE(attr_date) >'$date1'
Can you use the mysql FROM_UNIXTIME function dev.mysql.com - function from_unixtime
SELECT *
FROM 'table'
WHERE FROM_UNIXTIME(intTimestamp)
BETWEEN
date ('Y-m-d' , strtotime ( '15-10-2011') )
AND ('Y-m-d' , strtotime ( '01-11-2011'));
I had made a mistake with the date input but have fixed.

Categories