954,568 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Displaying last 6 months from current month php

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 ?

bala2111
Newbie Poster
7 posts since Sep 2011
Reputation Points: 10
Solved Threads: 0
 
SELECT * 
FROM `tablename` 
WHERE date_add( current_date(), INTERVAL -1
MONTH ) < date_colname
urtrivedi
Nearly a Posting Virtuoso
1,306 posts since Dec 2008
Reputation Points: 257
Solved Threads: 270
 

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

bala2111
Newbie Poster
7 posts since Sep 2011
Reputation Points: 10
Solved Threads: 0
 

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("", $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))
diafol
Rhod Gilbert Fan (ardav)
Moderator
7,792 posts since Oct 2006
Reputation Points: 1,170
Solved Threads: 1,080
 

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 .

pritaeas
Posting Expert
Moderator
5,480 posts since Jul 2006
Reputation Points: 653
Solved Threads: 875
 

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

bala2111
Newbie Poster
7 posts since Sep 2011
Reputation Points: 10
Solved Threads: 0
 

Just change the loop in ardav's code:

for ($i=5; $i >= 0; $i--){
pritaeas
Posting Expert
Moderator
5,480 posts since Jul 2006
Reputation Points: 653
Solved Threads: 875
 
for ($i = 5; $i > 0; $i--) {
  echo date('F, ', strtotime("-$i month"));
}echo date('F');


I used Pritaeas' code to giveApril, 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.

diafol
Rhod Gilbert Fan (ardav)
Moderator
7,792 posts since Oct 2006
Reputation Points: 1,170
Solved Threads: 1,080
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: