I have created a simple form which users submit. Everything works great but I recently found that the
SELECT * FROM `Forms` WHERE `Date` BETWEEN '{$startDate}' AND '{$endDate}'
The column Date is type TEXT. I needed it to be text cause I thought it would be easier to display everything in MM/DD/YY format. Now I dont want to risk changing the data type since the form is working fine.
Example of Date column
01-03-2013
01-04-2013
07-25-2012
08-01-2012
08-01-2012
08-01-2012
08-01-2012
Ex of working Query
SELECT * FROM `Forms` Where `Date` Between '01-08-2012' and '12-12-2012'
Ex of not working Query
SELECT * FROM `Forms` Where `Date` Between '01-08-2012' and '01-04-2013'
Any reason why it would break if the year changes? How can I get it to work even if the year changes.
you can do it like that
SELECT * FROM `Forms`
WHERE str_to_date(`Date`, '%d-%m-%Y') BETWEEN '2012-01-30' AND '2013-09-29'
DEMO HERE
EDIT :
if you want fix your table here how you do
Add a new column of the appropriate DATE data type:
ALTER TABLE `Forms` ADD `new_date` DATE AFTER `Date`;
Use MySQL's STR_TO_DATE() function to populate that new column with the dates held in the old column:
UPDATE `Forms` SET `new_date` = STR_TO_DATE(`Date`, '%d-%m-%Y');
Drop the old column (and, if so desired, rename the new one in its place):
ALTER TABLE `Forms` DROP `Date`, CHANGE `new_date` `Date` DATE;
Change your application to use this new column.
Because your column is a TEXT column MySQL will use an alphabetic compare.
01-08 comes before 01-04 so it's actually the month part already that breaks.
To fix this, either convert the column to a DATE type or reverse the order of the date to YYYY-MM-DD, in both cases the BETWEEN should function correctly.
Try this::
SELECT * FROM `Forms` Where str_to_date(`Date`, '%d/%m/%Y') Between '01-08-2012' and '12-12-2012'
If you are worried about it breaking then export the database then make the change. You won't get what you expect because it is a TEXT field not a date field. MySQL is sorting per character. As in it is looking at the first character then the next then the next.
Like navnav said it won't break but make a backup just encase.
As for displaying only the date you can explode() on a space to get only the date:
<?php
list($date, $time) = explode(" ", $datetime, 2);
echo $date;
?>
try this:
select * from "forms" where Date('column_name') between '' and ''
Related
when I fetch data from table "like date from 01/09/2017 to 30/09/2017" then it's okey..
BUT When I am trying to fetch data from date 01/09/2017 to 01/10/2017 then its only showing the data of DATE 01/10/2017(not previous month data i.e 01/09/2017)
I am using MySQL Database.
SELECT * FROM `tablename` where date between '01/09/2017' AND '01/10/2017'
If you are saving the value as DATE format it should work. If not (you are saving the data as VARCHAR you can convert it to date and get the correct results.
STR_TO_DATE('01/09/2017', '%m/%d/%Y')
You need to store dates as DATE type not VARCHAR or TEXT.
Also DB dates are in the format YYYY-MM-DD usually so you will need to adjust your query accordingly.
Due to speed trying to use STR_TO_DATE is a terrible idea, better to convert once and then use MySQL as intended.
Backup your data first and then I (think) the following will work
BEGIN;
ALTER TABLE `tablename`
ADD COLUMN `new_date` DATE;
UPDATE `tablename`
SET `new_date` = STR_TO_DATE(`date`, '%d/%m/%Y');
ALTER TABLE `tablename`
DROP COLUMN `date`;
ALTER TABLE `tablename`
CHANGE COLUMN `new_date` `date` DATE;
COMMIT;
Step By Step -
Add an extra column to store the data temporarily
Update the table and copy the current date column value (formatted
DB friendly date) into the new temp column.
Remove the old column
Change the column name to the previous name so all existing queries work.
Then your query is as simple as
SELECT * FROM `tablename` where date between '2017-09-01' AND '2017-10-01'
According to your example you have stored date as text so you need to apply STR_TO_DATE() to perform date operations
Try below query:
SELECT * FROM `tablename` where STR_TO_DATE(date,'%d/%m/%Y')between
STR_TO_DATE('01/09/2017','%d/%m/%Y') AND STR_TO_DATE('01/10/2017','%d/%m/%Y');
I have a datetime() column date_time in my database.
I need to convert this to date() and create a new temporary column date_field till the session ends.
I've tried this:
$query1 = SELECT date_time, date(date_time) as date_field FROM table_name....
This works and creates a temp column date_field with all the date values for the date_time field
Problem : This only works for this query. I also have another query which searches for date_time field and thus results into a DB error Unknown field 'date_field'.
$query2 = SELECT date_field FROM table_name
| This table doesn't have date_field as a column
Can this field be created so that I can use this for a time till the session ends ? as we do for temporary tables ?
Note: I can't use ALTER to add new column here due to code limitations.
Any ideas ?
Thanks!
In the first query, you dont really create any column, you just return a a column (date_time), run some function on it (date()) and give it an alias name (date_field). This happens only in the result set, and abvioysly cant be used outside of this query.
What you need to do is simply use the same in the second query: instead of select date field you need select date(date_time) as date_field
I have a table where the dating is not standard and need to somehow organise the rows by date and time.
job_date | job_time
=========================
12/12/2012 | 10.30am
11/10/2012 | 9.00pm
14/11/2012 | 11.50pm
Is there any way of formatting these within mysql. I have looked at the DATE_FORMAT() function but the examples I have found don't seem to relate to the format within my tables.
SELECT *, STR_TO_DATE(CONCAT(job_date,' ',job_time), 'Y-m-d H:i:s') AS date_format from table ORDER BY date_format DESC
The key method is STR_TO_DATE.
I will give you two solutions :
first : if you don't want to change your database :
SELECT jobdate, STR_TO_DATE(job_time,'%h:%i%p')AS real_job_time FROM yourtable ORDER BY real_job_time;
second : if you can modify your database, use the TIME format :
ALTER TABLE yourtable
MODIFY COLUMN job_time TIME NOT NULL;
UPDATE yourtable SET job_time = STR_TO_DATE(job_time,'%h:%i%p');
and to select
SELECT jobdate,job_time FROM yourtable ORDER BY job_time
I think the second solution is by far the best and that you should choose it.
Obviously storing it as a correct date would be a lot better and result in quicker queries.
SELECT *
FROM table
ORDER BY substr(job_date, -4), substr(job_date, 4, 2), substr(job_date, 1, 2)
I have a date field on my Sql table that is actually a text field, thats because there sometimes I save dates like 10/28/2011 and sometimes strings like present.
It is possible without touching the table structure, and maybe just with the sql query having the result correct organanized by date? Where present is the max value and then the dates in decreasing order.
If you really can't sort the data type out on those string date columns then this might help:
select t.*,
case when date_end = 'present' then curdate()
else convert(concat(substr(date_end,7,4),'-',substr(date_end,1,2),'-' ,substr(date_end,4,2)),date) end as "realDate"
from myTable t
order by "realDate" desc;
Right. I'm off to go and say 100 Hail Marys to the MySQL database god now. Ugh.
Best way would be :
fix the db and add proper date fields (add proper date or datetime field and update values from text fields and format them to be dates on the fly)
keep your present status in a text field and you can use that as a extra condition
I know you asked for a way to sort it correctly as a text column, but I really don't think that's the right way to this.
I agree with #stivlo. It is very easy to update the database to deal with this is a better way. You can either:
Convert the column to a real date, and use NULL to represent "present" instead of the string "present".
Or, if you need NULL reserved for some other meaning, you can convert the column to a real date, and add additional boolean flag columns to specify when the dates are "present".
Either way, you should definitely convert those text fields to real dates.
select job_desc, data_begin, data_end from table where data_end = 'present'
union
select job_desc, data_begin, cast(data_end as date) data_end from table where data_end <> 'present' order by data_end desc
Not sure if syntax is completely correct, so you might want to check the mySql 'union' syntax
Another solution might be using coalesce for 'present':
select cast(coalesce(data_end,now()) as date) data_end from table order by data_end desc
this way the column gets interpreted as dates and 'present' gets replaced with the present date
how to get latest date and time in php and mysql using a select statement? is that possible
My field type is data time
it looks like this "2010-06-08 01:41:27" . any help is appreciated guys.
edit:
sorry not so clear with my question...(ugh!)
basically I have a column in my table which has a field of datetime (did I say it right, it has a data type of datetime?) , these are fill up already with some data , All I need to do is get the latest in that field, is there a need to compare it ?
i think you are looking for this:
select max(datetime_column) from table
But your question isn't all that clear.
In SQL, use this:
SELECT NOW();
to get the current date/time. In PHP, use the time() function.
You can also insert the current time into a database field using this SQL:
INSERT INTO `mytable` (`date`) VALUES (NOW());
use Select now()
this may help u
for getting any value
If you want to see the record with the latest datetime column in it, do this:
select * from your_table order by your_datetime_column desc limit 1;
With your question, it shows that you really wanted to get the latest input from your database which has the present date and time. I think this should solve your problem
SELECT * FROM table_name WHERE DATE(`date_and_time_column_name`)= CURDATE();
This will surely do the job.