Fetch last 7 days data from current date

Asked

Viewed 32,219 times

19

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

$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 taking into account the months and years. There is some easier way to do this?

3 answers

24


If you want to search from the current date, you do not need to enter any date variable. Mysql is smart :), and is able to account for when it is seven days in the past.

Do so:

SELECT * 
FROM tabela 
WHERE 
  data BETWEEN CURRENT_DATE()-7 AND CURRENT_DATE()  

BETWEEN returns what is between these dates.

CURRENT_DATE() returns the current date.

CURRENT_DATE()-7 returns the current date, minus seven days.

References:

  • Thank you for the reply! ;)

8

Add this clause WHERE will take the current date and subtract 7 days, remembering that your date field, has q be of type date msm

  $query = mysql_query("SELECT * FROM tbl_registos WHERE data BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()");
  • 1

    in which case you’ll return all the valuables instead of the last 7 days

3

$sql = "SELECT * FROM Tabelas WHERE Campos BETWEEN CURDATE() AND CURDATE() + INTERVAL 7 DAY";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.