Retrieve records from this month
Friday, September 30th, 2005Recently I needed a method to pull all records from the current month out of a database to include in an email report. Originally I built this solution in Lasso/MySQL and have ported it over to PHP/MySQL for use with a personal project.
Initially the SQL code with hardcoded values:
[code lang=”SQL”]
SELECT * FROM table WHERE DATE_FORMAT(date_column,’%Y-%m-%d’) between DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND NOW()
[/code]
Then we use the formated php date function to get the day of the month. This way instead of hardcoding the value of days to “interval” or go back we can simply have today’s day of the month input into the sql statement.
[code lang=”PHP”]
$getLastMonth = date(”j”); //Get the current day of the month
[/code]
All together now:
[code lang=”PHP”]
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( “Unable to select database”);
$getLastMonth = date(”j”);
$query = “SELECT * FROM table WHERE DATE_FORMAT(date_column,’%Y-%m-%d’) between DATE_SUB(CURDATE(), INTERVAL $getLastMonth DAY) AND NOW()”;
mysql_query($query);
mysql_close();
[/code]