I have users in a MySQL database, where their birthdays are stored in a DATE
format (yyyy-mm-dd). I want to select users in the database with PHP who are between a certain age range.
What I have is a minimum age(18) and a maximum age(21). I know I can do something with BETWEEN, but the problem is that I only know the years and not the dates.
Does anyone have a suggestion on how I can do this?
This is what I'm doing currently:
function leeftijden($age) {
$morgen['day'] = date('d');
$morgen['month'] = date('m');
$morgen['year'] = date('Y') - $age;
$datum = $morgen['year'] .'-' .$morgen['month'].'-' .$morgen['day'];
return $datum;
}
Then I do this:
$maxDatum = leeftijden(18);
$minDatum = leeftijden(32);
$sqlRijder = "SELECT * FROM rijder WHERE geboortedatum between '".$minDatum."' AND '".$maxDatum."'";
But this doesn't work 100%.
How can I only select users who are between 18 and 21 years of age?
You can simply do it right in the query:
SELECT *
FROM rijder
WHERE geboortedatum BETWEEN
CURDATE() - INTERVAL 21 YEAR AND
CURDATE() - INTERVAL 18 YEAR
This way, you do not need a special PHP function to construct a DATE string. Simply pass in the numbers and MySQL will make the comparisons for you. Just make sure the higher number comes first in the BETWEEN
.
Try this :::
Select * from table where (DATEDIFF(dob, DATE(NOW())) / 365.25) between 18 and 21
SELECT * FROM rijder
WHERE geboortedatum
between date_add(curdate(), interval -18 year)
and date_add(curdate(), interval -21 year)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With