Question:
I'm doing a DB query, and I want to receive results for the last 7 days from the current date. For that, I have a data
field of DATA type (yyyy-mm-dd) in the table. I'm doing the query in php turn mysql.
$query = mysql_query(SELECT * FROM tbl_registos WHERE data >= '$last_7_days');
The variable $last_7_days
must be the value of the last 7 days, always keeping in mind the months and years. Is there an easier way to do this?
Answer:
If you want to search from the current date, you don't need to enter any date variables. MySQL is smart :), and is able to count when it's seven days in the past.
Do like this:
SELECT *
FROM tabela
WHERE
data BETWEEN CURRENT_DATE()-7 AND CURRENT_DATE()
BETWEEN
returns what's between these dates.
CURRENT_DATE()
returns the current date.
CURRENT_DATE()-7
returns the current date minus seven days.
References: