date between in mysql not correctly working - php

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');

Related

Add new column into mysql from another column from select statement

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

Convert and Store Date and Time in other coloumn in MySQL

I have database in MYSQL with ID, Req_Order_No(Varchar) , Req_In_Time(DateTime), Req_Out_Time(DateTime)
The Sample row is like below:
1 W0CH546 2014-07-23 09:32:00 2014-07-24 01:42:00
The above Date and Time are in EST format. I want to convert both of them and store in IST format in other columns
I tried SELECT CONVERT_TZ('Req_In_Time','-05:00','+9:30');
But it returns NULL Values.
Please help. Do I need php also?
The quotes around Req_In_Time cause the error.
SELECT CONVERT_TZ(Req_In_Time,'-05:00','+9:30');
Also, you should never store time information in localtime.
Use UTC/GMT.
You can always convert it to the proper localtime when you display it.
Note: Of course you need to specify the table-name as well:
SELECT CONVERT_TZ(Req_In_Time,'-05:00','+9:30') FROM YOUR_TABLE_NAME;
So you add another column (e.g. column xxx) to YOUR_TABLE_NAME.
Then you update the values.
UPDATE YOUR_TABLE_NAME
SET xxx = CONVERT_TZ(Req_In_Time,'-05:00','+9:30')
BTW, to add the column:
ALTER TABLE YOUR_TABLE_NAME ADD COLUMN `xxx` datetime NULL ;

MYSQL Select between date breaking on year

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 ''

Date when record was created in mysql datatabase

I have table in which I have birthdate , age location and Score and I want to retrieve the count of number of records created between two dates where score is not null and there is no time stamp field.
How can I do it if there is no time stamp field.
Is there any meta data and if it is , how can I run the query?
try a query like this:
SELECT COUNT(*)
FROM TABLE_NAME
WHERE BIRTHDATE BETWEEN 'DATE1' AND 'DATE2'
AND SCORE IS NOT NULL AND TIMESTAMP IS NULL;
Add a column timestamp to the existing table, with default value as NULL, and query the above statement, it should work.
Whenever you add a column, to a table already having records, the corresponding values are blank for that new column, for existing records.
Add a timestamp to your tables
Echoed here as other users have noted.
Because you have no date reference field in the database, you can't pull out records that match one or that are between two dates.
Your best bet from here on in, is to add a date field and then make sure when data is written to the DB, you insert a date/datetime using mysql now() function. There are a few different ways to achieve it, but this is probably the easiest:
mysql_query("
INSERT INTO users (first, last, whenadded)
VALUES ('$first', '$last', now())
";

Insert users join date into the database

How would I go about adding the current date into the database (MySQL) when a user registers? I know I would need to add a row in the database (Join_date or something), what would I set that to when creating that row? timestamp? varchar?
I want to make it so when the user submits the registration form it adds the current date to the join date row.
Any help would be greatly appreciated.
Thanks.
Suppose structure is
field type
++++++++++++++++++++++
id INT
username varchar(10)
password varchar(10)
date datetime
Then use below query
INSERT INTO Table values (1,'username','password',NOW())
Hope this helps you...
Column type should be datetime
and while inserting row, use NOW() in query
Add a datetime column, and use NOW()doc to set the column when inserting a record.
This was asked many times.
See this question: Registration date . Its solution can be used well; it will automatically insert date.
Add a column TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
Make that field either MySQL internal date/time type (see http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html) and use CURRDATE (http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html) to fill it, or simply make it int and fill it with POSIX time with time().
Personally I find the Unix timestamp better since it's easier to operate and it doesn't depend on the type of db.
You can use a code like this
INSERT INTO users (LastName, FirstName, DateColumn)
VALUES ("firstname", "lastname", NOW())
NOW() would insert the current date in the DateColumn field
try this:
INSERT INTO users (`LastName`, `FirstName`, `DateColumn`)
VALUES ("Fname", "LNamee", NOW())
assuming that you are using mysql, you can use field type DATETIME or TIMESTAMP.
usually I use DATETIME for created ("join date") fields and TIMESTAMP for lastupdated field, since it can be (easily) populated transparently by the RDBMS on update.
To get the current date you can use mysql function NOW().
for example:
INSERT INTO Users (`firstname`, `regdate`) VALUES ('herbie', NOW());

Categories