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?

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'");
?>

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

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);

Try echoing your query and running it manually:

 

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

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 :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.