I want to display last 6 months from the current month.

For example This month is september, I want to display April, May, June, July, August, September

Can anyone help me with this ?

SELECT * 
FROM `tablename` 
WHERE date_add( current_date(), INTERVAL -1
MONTH ) < date_colname

Thanks for your reply...but i wanna do it only with php..not with mysql.!

Member Avatar for diafol

There may be a nifty little function for this, but perhaps this would be easier:

$m = date('n');
for($i=0;$i<6;$i++){
  $m_array[] = date('F', mktime(0,0,0,$m-$i,15,2011));//you could echo here, but may be handy to place in an array. Also the day (15) and year (2011) do not matter - I just picked 15 as it's a mid-number for months.
}
echo implode("<br />", $m_array);

The nice bit about this is the $m-$i. mktime understands month #3 (March) - 5 months.
current month of March will give March,Feb, Jan, Dec, Nov, Oct.

If you want the years as well, just set the current year:

$y = date('Y');
...
$m_array[] = date('F', mktime(0,0,0,$m-$i,15,$y))

This should work in PHP, but am unable to test right now:

echo date('F');
for ($i = 1; $i < 6; $i++) {
  echo date(', F', strtotime("-$i month"));
}

From the manual.

thank you so much ardav, it works like a charm...is it possible to display from April to september ? as the code displays september to april

Member Avatar for diafol
for ($i = 5; $i > 0; $i--) {
  echo date('F, ', strtotime("-$i month"));
}echo date('F');

I used Pritaeas' code to give April, May, June, July, August, September

I think Pritaeas' code is cleaner than mine. I don't really like those 'placeholder' day and year values in the mktime() - they're really ugly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.