Search the data for the last 7 days from the current date

17

I am making a query to DB, and I want to receive results for the last 7 days from the current date. For this, I have a data field of type DATA (yyyy-mm-dd) in the table. I'm doing the query in php, mysql turn.

$query = mysql_query(SELECT * FROM tbl_registos WHERE data >= '$last_7_days');

The variable $last_7_days should be the value of the last 7 days, always keeping in mind the months and the years. Is there any easier way to do this?

    
asked by anonymous 14.03.2014 / 12:59

3 answers

22

If you want to fetch from the current date, you do not need to enter any date variables. MySQL is smart :), and is able to make the count of when it's seven days in the past.

Do 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:

14.03.2014 / 13:09
7

Adding this clause WHERE will get the current date and subtract 7 days, remembering that its date field, must be of type date msm

  $query = mysql_query("SELECT * FROM tbl_registos WHERE data BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()");
    
14.03.2014 / 13:06
3
$sql = "SELECT * FROM Tabelas WHERE Campos BETWEEN CURDATE() AND CURDATE() + INTERVAL 7 DAY";
    
14.03.2014 / 16:35