Reputation: 546
I have a invoice type form submission and every submission has a date so I have created a varcha date field in mysql database to save the time.Time format is like '2011-06-26'.Now I need to select a range based on the date from my database.I tried following options but they don't display any result just blank page is displayed,even no errors.
Should I follow some special techniques on saving date to my database.If so please give me some explain about that because I am new to PHP and MYSQL development.
SELECT * FROM table_name
WHERE 'date'
BETWEEN UNIX_TIMESTAMP('2011-06-02') AND UNIX_TIMESTAMP('2011-06-25')
SELECT * FROM my_table
WHERE 'date'
BETWEEN CAST('2011-06-02' AS DATE) AND CAST('2011-06-25' AS DATE)";
This is what I used to extract data
$result=mysql_query($query);
while($row=mysql_fetch_array($result)){
echo $row['tax']."<br>";
}
Thank you.
Upvotes: 3
Views: 36351
Reputation: 2269
If you use DATETIME
type to store your date the trick is simple.
DATETIME
allows you to store the date and the timestamp, however if only the date is specifed, timestamp will be stored as 00:00:00
I'll show you a simple example.
mysql> CREATE TABLE test_table(
id INT UNSIGNED AUTO_INCREMENT,
test_date DATETIME,
PRIMARY KEY (id));
mysql> INSERT INTO test_table(test_date)
VALUES('2011-06-26'), ('2011-05-14'), ('2011-05-02');
mysql> SELECT * FROM test_table;
+----+---------------------+
| id | test_date |
+----+---------------------+
| 1 | 2011-06-26 00:00:00 |
+----+---------------------+
| 2 | 2011-05-14 00:00:00 |
+----+---------------------+
| 3 | 2011-05-02 00:00:00 |
+----+---------------------+
mysql> SELECT * FROM test_table WHERE test_date
BETWEEN '2011-05-01' AND '2011-05-31';
+----+---------------------+
| id | test_date |
+----+---------------------+
| 2 | 2011-05-14 00:00:00 |
+----+---------------------+
| 3 | 2011-05-02 00:00:00 |
+----+---------------------+
That's it.
Upvotes: 11
Reputation: 24248
date
as DATE)
BETWEEN CAST('2011-06-02' AS DATE) AND CAST('2011-06-25' AS DATE)";Upvotes: 2
Reputation: 5685
If the date column is of the TIMESTAMP or DATETIME type then the query should be:
SELECT * FROM table_name
WHERE 'date'
BETWEEN '2011-06-02' AND '2011-06-25'
Edit: Sorry didn't see the column was a VARCHAR - you should change it to the DATETIME type to make things simpler.
Upvotes: 2