简体   繁体   中英

PHP mysql select date range

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.

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.

  1. Name of column - or without or in backticks
  2. If date is varchar - also need cast date SELECT * FROM my_table WHERE cast( date as DATE) BETWEEN CAST('2011-06-02' AS DATE) AND CAST('2011-06-25' AS DATE)";

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM