tags:

views:

145

answers:

2

I am currently working in an site which needs to get the birthdays of friends who are celebrating their birthday this week, this month and next month using MYSQL and PHP.

How would I go about this?

+3  A: 

Provided you store birthdates in DATE (or DATETIME) format in MySQL you can use the following Queries:

// This week
SELECT * FROM person WHERE WEEK( birthdate ) = WEEK( NOW() )

// This month
SELECT * FROM person WHERE MONTH( birthdate ) = MONTH( NOW() )

// Next month

SELECT * FROM person WHERE MONTH( birthdate ) = MONTH( NOW() ) + 1;

SELECT * FROM person WHERE IF
  ( MONTH( NOW() ) < 12, MONTH( birthdate ) = MONTH( NOW() ) + 1,
  MONTH( birthdate ) = 1)
Anax
Your next month query will not work in December as `MONTH(NOW()) + 1 = 13`
RaYell
Well spotted. The correct answer would be something like:SELECT * FROM person WHERE IF ( MONTH( NOW() ) < 12, MONTH( birthdate ) = MONTH( NOW() ) + 1, MONTH( birthdate ) = 1)Thanks for the remark.
Anax
For a person born on `Mar 1st`, this will return true during the whole `March`.
Quassnoi
This condition: `MONTH('2009-03-01') = MONTH(CURRENT_DATE)` holds for every date of `March`. `MONTH('2009-03-01')` returns `3` and same does `MONTH(CURRENT_DATE)`.
Quassnoi
Is there any possible way to get the age of the friends with this query...
Fero
You can take the "simple" approach: SELECT YEAR( NOW() ) - YEAR( birthdate ) AS age FROM personor you can be more precise: SELECT YEAR( NOW() ) - YEAR( birthdate ) - IF( DATE_FORMAT( NOW( ) , "%m%d" ) < DATE_FORMAT( birthdate, "%m%d" ), 1, 0 ) AS age FROM person
Anax
A: 
SELECT  *
FROM    users
WHERE   birthday + INTERVAL YEAR(CURRENT_DATE) - YEAR(birthday) YEAR BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL 3 DAY

Note that this condition is not sargable and requires full indes scan.

In SQL Server, Oracle and PostgreSQL this can be improved using this approach:

, but MySQL lacks a way to generate a random resultset.

However, you can create a dummy table and store years from 1900 to 2100 in it.

Add a cron task to update it in 2100 since you can forget easily :)

Quassnoi