tags:

views:

71

answers:

4

I'm doing a search through a database to find articles written within a certain month:

between '1 '.$month.' '.$year and '31 '.$month.' '.$year

Is this method ok even if some months (like February) only have 28 days? In other words, do I have to dynamically find the number of days in the month, or not?

+6  A: 

No, you don't need to know the lengths of the months. Just do this:

WHERE MONTH(yourcolumnname) = $month AND YEAR(yourcolumnname) = $year
Mark Byers
And the `$year` part?
Joren
@Joren. Thanks, fixed.
Mark Byers
what type of field would it have to be for this to work?
WillyG
DATE, DATETIME, or TIMESTAMP - one of the column types that MySQL knows as a date, in other words. I don't believe you could do this on a VARCHAR column or anything.
ceejayoz
@ceejayoz: In MySQL it also works on VARCHAR. It just returns NULL if the string isn't a valid date.
Mark Byers
@Mark Byers Thanks, good to know. Imagine it'd be *faster* on one of the date types, though, as it doesn't have to guess/interpret.
ceejayoz
so if my column was a timestamp column, would I replace datetime with timestamp?
WillyG
iMaster: 'datetime' was a placeholder for the *name* of the column, not the type.
Mark Byers
@iMaster: There is a reason I asked you in a comment to your question to provide more information about the name and type of your column. If you just tell us that information instead of leaving us to guess it, it will make it a lot easier to help you in an efficient way.
Mark Byers
A: 

Can you search between

between '1 '.$month.' '.$year and '1 '.$month_plus1.' '.$year

?

Have you tried running your sql statement against the data you are trying to match, that might be a good approach to begin with.

Toby Allen
That'd include the first day of the next month, which I imagine would be suboptimal.
ceejayoz
if you include time, it would be feasible to use this method also !... I use to add a month and substract a second or a millisecond
Jhonny D. Cano -Leftware-
+1  A: 

Your code looks o.k. in the sense that it will work, but a more elegant approach would be

SELECT * FROM tablename WHERE MONTH(columname) = '1'
                              AND YEAR(columnname) = '2009'
Pekka
+1  A: 

If it's a DATETIME or DATE field, you could also do SELECT * FROM table WHERE date_column LIKE '2010-02-%'; With indexing, this may be faster than the MONTH() and YEAR() technique, which'll have to run a calculation on each row.

ceejayoz