Speedwheelftw
Speedwheelftw

Reputation: 393

php - compare date with database (birthdate)

So I have a row called birthday in the database with the value of let's say 2001-04-25 (DATE type). And I want to see if it's a user birthday. I get current month and day:

$monthday_today = date('m-d');

And than do the query:

$query = "SELECT * FROM users WHERE DATE_FORMAT(birthday, '%m-%d')=".$monthday_today;

But it doesn't works, any thoughts?

Upvotes: 0

Views: 506

Answers (2)

Mihai Stancu
Mihai Stancu

Reputation: 16107

You need to quote the $monthday_today value.

You query (if you would output it) would look like this:

SELECT * FROM users WHERE DATE_FORMAT(birthday, '%m-%d') !=  04-2014

But this is not a correct SQL query, the query should look like this:

SELECT * FROM users WHERE DATE_FORMAT(birthday, '%m-%d') !=  '04-2014'

The simple solution would be:

$query = "SELECT * FROM users WHERE DATE_FORMAT(birthday, '%m-%d')!="."'".$monthday_today."'";

The good solution would be to use parameterized prepared statements with either positional or named parameters:

$query = "SELECT * FROM users WHERE DATE_FORMAT(birthday, '%m-%d') != ?";

Or

$query = "SELECT * FROM users WHERE DATE_FORMAT(birthday, '%m-%d') != :monthday_today";

You don't need to quote parameterized prepared statements because they will infer (deduce) if quoting is necessary or not by the type of the variable.

Upvotes: 3

Anticom
Anticom

Reputation: 1013

There's an even simpler solution that doesn't require PHP:

$query = "SELECT * FROM users WHERE YEAR(birthday) = YEAR(NOW()) AND MONTH(birthday) = MONTH(NOW())";

Upvotes: 1

Related Questions