SELECT * FROM logs;
idDate accNum idMonths dDay dYear dType transacted_money dat
4 862065095 9 8 2015 Withdraw 2323 09/08/2015
5 862065095 9 8 2015 Deposit 333 09/08/2015
Please help me solve this problem I wanted to get the data so that I could manipulate them in PHP. But first I would like to test my query in mysql and that's what it came out. Theres no result. Why? is my query wrong ?
Well I guess my first picture was deleted the actual query that was done was
SELECT * FROM logs WHERE dat BETWEEN '9/8/2015' AND '9/13/2015';
Your dates are strings, not actual mysql dates, so they're being compared by STRING rules, which means:
'9/1/15' > '10/1/15' --> TRUE (september comes after october?)
because 9 is bigger than 1 in a string context.
Note that
'2015-09-01' > '2015-10-01' -> FALSE
Either fix your table to convert those varchar fields into proper date/datetime fields, or you'll have do silly hacks like
WHERE str_to_date(varcharfield, ...) BETWEEN '2015-09-01' AND '2015-10-'01'
note the format the dates in the above example. MySQL expects/requires dates to be in yyyy-mm-dd or yyyy-mm-dd hh:mm:ss format to parse them as dates. Anything else is simply a string.
mysql> select '9/1/15' > '10/1/15', '2015-09-01' > '2015-10-01';
+----------------------+-----------------------------+
| '9/1/15' > '10/1/15' | '2015-09-01' > '2015-10-01' |
+----------------------+-----------------------------+
| 1 | 0 |
+----------------------+-----------------------------+
1 row in set (0.00 sec)
Try using the following
WHERE DATE_FORMAT( `createdon` , '%Y-%m-%d' ) <= '2014-07-31'
AND DATE_FORMAT( `createdon` , '%Y-%m-%d' ) >= '2014-07-01'
31-07 is end date and 01-07 is start date
As several users pointed out this is a very bad way to do it since your dates are strings and don't follow the correct way mysql formats dates, but since you asked for it this is a way to do it:
SELECT * FROM test
WHERE
STR_TO_DATE(my_date, '%m/%d/%Y') BETWEEN '2015-09-09' AND '2015-09-12';
Demo.
P.S. To use BETWEEN you must provide a date like yyyy-mm-dd or yyyy-mm-dd hh:mm:ss.
Related
I have a table called reports in MySQL(MariaDB) . There is a one(out of 5) column named logdate which is is of type datetime .columns stores the the date and time (in 24hr format) .
for ex here is sample value from that column
2021-04-10 09:35:00
I have to find all reports between a given date and time .
I get 4 variables from form data in PHP
$fromdate= $_POST['fromdate'];
$todate= $_POST['todate'];
$fromtime= $_POST['fromtime'];
$totime= $_POST['totime'];
$fromtime and $totime are just integers with value from 0-23 for hours.
For example the condition may be like get all data between 4th April 2021
from 5 o'clock To 8 April 2021 18 o'clock
i.e. From 2021-04-04 03:00:00 to 2021-04-08 18:00:00. There will be never condition on minutes and seconds .
My question is how to construct a datetime in PHP compatible with MySQL types so I can have good(efficient, there are millions of records in table ) search speed?
for ex
$select = "select * from reports where logdate between ? and ? ";
P.S: I tried saving date and time as integer as unixtime stamp. But when i convert from and to date received using strttotime() I facing time format issue due to bug in my code which so can use datetime only.
If you have any suggestion to improve efficiency of DB please suggest.Thanks
Hi this link may be of help in optimizing date comparison
MySQL SELECT WHERE datetime matches day (and not necessarily time)
This one below, will help you in formatting your strtotime() by using strptime()
https://www.php.net/manual/en/function.strptime.php
Also check your spelling or typo; you wrote "strttotime()" instead of "strtotime()" yours has an extra 't' in str"tto"time, it should be str"to"time, though without the double qoutes
Though I can't say for sure this is the most effective way but you can use hour(logdate) to compare with $fromdate and $todate
$select = "select * from reports where hour(logdate) between ? and ? ";
But it will only compare hour part. Please mention how you are getting date part to compare?
It is not a good idea to make a calculation on a field in the WHERE CLAUSE. In this case MySQL / MariaDB must calculate the value from this field to comapare it to see
if this ROW has this condition. So MySQL must read the whole table FULL TABLE SCAN and CANT use any INDEX.
A better way to do this is to store the calculation on fix site. Then MySQL calculated it only one time and can use a Index ( if there one) .
you can easy use a query like this:
$select = "SELECT * FROM reports where logdate between date(?) + INTERVAL ? HOUR AND date(?) + INTERVAL ? HOUR ";
to test see:
SELECT date('2021-04-05') + INTERVAL 16 HOUR;
result:
2021-04-05 16:00:00
Here is what is working for me after using Bernds solution .
I constructing datetime string in php
$fromstr ="$fromdate"." "."$fromtime".":00:00";
$tostr="$todate"." "."$totime".":00:00";
here is my query looks like for date of 7th April to 10th April
$ select = "SELECT * FROM reports where logdate >= '$fromstr' and logdate <= '$tostr' order by logdate";
after echoing it
"SELECT * FROM reports where logdate >= '2021-04-07 3:00:00' and logdate <= '2021-04-10 5:00:00' order by logdate";```
However I am not sure if can use index for logdate column and utilize it with above query.
I am trying to insert 2 dates in UK format (dd/mm/yyyy) to a MySQL database in the MySQL US date format.
I am using str_to_date. The first instance of str_to_date works as expected, but the second instance always inserts the same date as the first instance of str_to_date, even though the original dates are different.
$date_1 = "10/01/2016";
$date_2 = "16/02/2016";
$sql = "INSERT INTO customers (date_1, date_2)
VALUES (STR_TO_DATE( '$date_1', '%m/%d/%Y %h:%i' ), STR_TO_DATE( '$date_2', '%m/%d/%Y %h:%i' ))";
What is the correct way of handling multiple instances of str_to_date in a MySQL insert statement?
Thank you
The format string of str_to_date() tells MySQL what format the first argument's date value is in. It's not how to format the value going in to mysql (e.g. the destination) format. str_to_date's output is ALWAYS a native mysql date/time value, which is yyyy-mm-dd hh:mm:ss
Since you're saying the input format is monday/day, but are providing day/month values and NO time values, you get wonky results.
Try
24/01/2016
STR_TO_DATE( '$date_1', '%d/%m/%Y' )
instead. Note the removal of the time format characters. Your input string has no time values at all.
mysql> select str_to_date('24/01/2016', '%m/%d/%Y %h:%i');
+---------------------------------------------+
| str_to_date('24/01/2016', '%m/%d/%Y %h:%i') |
+---------------------------------------------+
| NULL |
+---------------------------------------------+
1 row in set, 1 warning (0.00 sec)
mysql> select str_to_date('24/01/2016', '%d/%m/%Y');
+---------------------------------------+
| str_to_date('24/01/2016', '%d/%m/%Y') |
+---------------------------------------+
| 2016-01-24 |
+---------------------------------------+
1 row in set (0.00 sec)
Date 1 :- 2014-09-27 10:00:00
Date 2 :- 2014-09-29 11:00:00
This range is stored inside the database and it means that user has given time range for 2 days from 27 to 29 and timing from 27 -> 10:00:00 to 29 -> 11:00:00. This means that user will be available from 10 AM to 11 AM between 27 to 29, 2014.
Now if i pass 2014-09-28 13:00:00 which is in date range and also in time range because user specified the entire day for it as can be seen in the range.
SELECT * FROM TABLE_NAME WHERE Id = $Id AND DATE('$currentDate') BETWEEN DATE(From_DateTime) AND DATE(To_DateTime) AND TIME('$timeHour') BETWEEN TIME(From_DateTime) AND TIME(To_DateTime)
From_DateTime = Date1
To_DateTime = Date2
currentDate = 2014-09-28
timeHour = 13:00:00
Now the problem is that logically the parameter passed are within the range but using the query its not because in TIME its not checking the date, 13 is not between 10 & 11 so its not working. I have tried the DATETIME as well but its not working as giving me error.
I need a way to match date & time both at the same time. Anyone having any suggestion. I am using PHP as programming language.
If the values are stored in DATETIME like this format you mentioned
Date 1 :- 2014-09-27 10:00:00
Date 2 :- 2014-09-29 11:00:00
Then you don't even need all that complexity. Just use normal comparison operators
SELECT * FROM yourTABLE
WHERE startDate >= '2014-09-27 13:00:00'
AND endDate <= '2014-09-29 10:00:00'
Ofcourse you can use your PHP variables instead of the test dates I have there in the query. You can format your PHP values to be in line with MySQL date time format.
If you're expecting large result or large database, I would suggest you use the "BETWEEN".
But I would like to clarify your database schema has 2 fields to compare? Namely "To_DateTime" and "From_DateTime"? If so, I seconded Hanky's answer.
I have to use a varchar field in a mysql database to store a date, and I need to be able to query on this date later on as if it was a date field.
What format should the date go into the database? date()?
How do I convert a string to a date in mysql?
Thanks!
As i seen from your comment you are using wordpress so in that already have function to use date with format which you want
use below LINK to get_option and also have default parameter to get. like
<?php echo get_option( $option, $default ); ?>
where $default = 'date_format' - Default date format; set in General Options.
let me know if i can help u more.
MySQL provides DATETIME data type. But CHAR or VARCHAR should be fine, depending on what you need.
For the format, this is the standard format as per wiki. YYYY-MM-DD HH:MM:SS, for date only, this should do: YYYY-MM-DD.
Also check out the STR_TO_DATE function.
Here is an example:
SELECT STR_TO_DATE('01,5,2013','%d,%m,%Y')
will return a date of
'2013-05-01'
Please read the documentation
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html
STR_TO_DATE()
If you just wanna query the data, as if it was a date, you can do it like this...
SELECT * FROM table1 WHERE DATE_FORMAT(STR_TO_DATE(yourColumn,'%m/%d/%Y %x:%x:%x'), '%Y-%m-%d 23:59:59') >= NOW()
This will select all readocrds that have a date greater than or equal to today
In my opinion there is no problem. If you like to store a date as varchar, it is okay. If you like to use the data with date functions later, it is also okay. The difference is only in the way MySQL stores the data. If you use varchar to store a date, you need more memory, but you can store other strings too. You can try it yourself:
mysql> SELECT YEAR("2013-06-18");
+--------------------+
| YEAR("2013-06-18") |
+--------------------+
| 2013 |
+--------------------+
1 row in set (0,00 sec)
You can even compare strings with dates like this:
mysql> SELECT DATE(NOW())="2013-06-18";
+--------------------------+
| DATE(NOW())="2013-06-18" |
+--------------------------+
| 1 |
+--------------------------+
1 row in set (0,00 sec)
If you don't trust this tests, you can first put the data into a test table with a field of type varchar. I have done it with the same result.
So basically I have a table -
ID | from | To
-----------------
1 | 25.05.2012|30.05.2012
-----------------
2 | 15.05.2012|20.05.2012
-----------------
3 | 25.06.2012|30.06.2012
and I have a query
SELECT date.*
FROM table AS date
WHERE (date.from >= '25.05.2012' OR date.to >= '25.06.2012' ) AND (date.to <= '30.05.2012' OR date.from <= '25.05.2012' )
GROUP by date.id
but it's not working, what could be the problem?
date is a reserved keyword in MySQL, try calling the table something else!
You are performing string comparisons, not date comparisons, eg: 26.05 is greater than 25.06 since the comparison only reaches as far as the second character of the string and determines that 6 is greater than 5.
In order to perform date comparisons you either need to store the value as a date (preferable) or in an appropriate string form eg yyyyMMdd.
SELECT * FROM table WHERE (from >= '25.05.2012' AND to <= '25.05.2012') GROUP by id;
"date" is a reserved string in MySQL. I'd recommend renaming all tables and columns with that name to a custom one. This might already solve your problem.
Point 1 : table, date, from are reserved keywords. Those should not be used for naming tables. If your table name is table, use backticks
Point 2 : When you have one table why you are creating alias for that?
Point 3 : While comparing date should be in format of yyyy-mm-dd. I believe from and to columns are timestamp.
Point 4 : No need of GROUP BY statement at the moment as you are not using any aggregate function such as SUM, COUNT, etc
Your query should be
SELECT *
FROM `table`
WHERE
(`from`>= '2012-05-25' OR `to`>= '2012-06-25' )
AND
(`to` <= '2012-05-30' OR `from` <= '2012-05-25');
If you want to pass date as 25.05.2012 , use STR_TO_DATE function to convert string to date.