tags:

views:

74

answers:

1

I've been trying to get upcoming birthdays using mysql statement and php. Problem is i've seen some solutions but they use date fields. Unfortunately mine is stored as timestamps. The code below only yields results if the birthdate is after 1970. How can I get a query that will give me current month, next month, month after and so on of upcoming birthdays? And how can I get it to ignore the year as well?

    $sql_query = "
        SELECT mem_id, DATE_FORMAT(FROM_UNIXTIME( birthdate ),'%d/%m/%Y') 
)
        FROM profiles
        WHERE
            IF ( MONTH( NOW() ) < 12,
              MONTH( DATE_FORMAT(FROM_UNIXTIME( birthdate ),'%Y%m%d') ) = MONTH( NOW() ) + 1,
              MONTH( DATE_FORMAT(FROM_UNIXTIME( birthdate ),'%Y%m%d') ) = 1)
        ORDER BY birthdate";
A: 
$currentMonth = date('n'); // or date('n', strtotime('+1 month')) or whatever
$query = "SELECT ... WHERE MONTH(FROM_UNIXTIME(`birthday`)) = $currentMonth";

Note though that UNIX timestamps are a terrible choice for storing birthdays:

  • They can not store dates prior to 1970 (unless you use negative numbers, which may not work everywhere).
  • To query for them in the database you have to convert all entries FROM_UNIXTIME to compare them, which is quite expensive.

You should use native MySQL DATE columns to store dates, which allows you to store a much wider range of dates and is much more efficient for queries.

deceze