I have this code to select from my database data from current month:
SELECT * FROM daily_reports
WHERE username = '$username' and MONTH(date) = MONTH(Now())
order by date DESC
And now i want to display data from last month.
column date is type date
This should work:-
SELECT *
FROM daily_reports
WHERE username = '$username'
and MONTH(date) = MONTH(DATE_ADD(Now(), INTERVAL -1 MONTH))
order by date DESC
SELECT
*
FROM
daily_reports
WHERE username = '$username'
AND dateColumn BETWEEN SUBDATE(CURDATE(), INTERVAL 1 MONTH) AND NOW();
ORDER BY DATE DESC
Try this
SELECT * FROM daily_reports
WHERE username = '$username'
and MONTH(date) = MONTH(DATE_ADD(Now(), INTERVAL -1 MONTH)) order by date DESC
You can do many operations on dates, as shown in the fine manual.
In your case, perhaps the DATE_SUB function would be clearest:
SELECT * FROM daily_reports
WHERE username = '$username' AND MONTH(date) = MONTH(DATE_SUB(Now(), INTERVAL 1 MONTH)
ORDER BY date DESC
date BETWEEN date_format
(NOW() - INTERVAL 1 MONTH, '%Y-%m-01')
AND last_day(NOW() - INTERVAL 1 MONTH)