Jump to content

First Day & Last Day Of The Last 6 Months


refiking

Recommended Posts

I need to retrieve records from my db that are timestamped.  I need 6 different queries for the last 6 months.  I need all the records in a given month.  So, how do I code that exactly?  Here's what I have so far

 

$time = time();
$lastmonth = strtotime('-1 month');
$sql = mysql_query("SELECT * FROM reports WHERE time < '$time' AND time > '$lastmonth'");

 

That string won't give me exactly what I'm looking for so, what can I change or do i need to scrap the whole thing and start from scratch?

Link to comment
Share on other sites

I'm guessing you want the first second of the month to the last second of the month. Of so, try this:

 

<?php
$month = '2008-06-01'; //here's the month you want, as an example
$start = strtotime("$month 00:00:00");
$end = strtotime("$month 00:00:00 +1 month");
$sql = mysql_query("SELECT * FROM reports WHERE time BETWEEN '$start' AND '$end'");
?>

Link to comment
Share on other sites

OK.  So, here's the code I have so far:

 

$sepsql = mysql_query("SELECT * FROM records WHERE time BETWEEN '$jstart' AND '$jend'")or die(mysql_error());
$sepnum = mysql_num_rows($sepsql);

 

When I echoed results, here's what I got:

 

$jstart = 09-01-08 00:00:00

$jsend = 10-01-08 00:00:00

$sepnum = 0

 

$sepnum should have been 6

Link to comment
Share on other sites

Ah, sorry. Well, what format is your "time" column? Also, "time" is a keyword in SQL, so I suggest adding double quotes:

 

$sepsql = mysql_query("SELECT * FROM records WHERE \"time\" BETWEEN '$jstart' AND '$jend'")or die(mysql_error());
$sepnum = mysql_num_rows($sepsql);

Link to comment
Share on other sites

To get previous months ( in this example, 2 months ago )

 

SELECT
 `your`, `columns`, `here`,
 @then := DATE_SUB( NOW(), INTERVAL 2 MONTH ) as `prev_date`
FROM
 `your_table`
WHERE
 MONTH( `vtime` ) = MONTH( @then )
   AND
 YEAR( `vtime` ) = YEAR( @then );

 

Man, I hate that. You spend WAY too much time on a problem, and someone comes up with some brilliantly simple solution like that. Nice, discomatt!

 

Thank you :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.