Select all users within a specific age range.

I have users in a MySQL database where their birthdays are stored in the format DATE(yyyy-mm-dd). I want to select users in a database with PHP who are between a certain age range.

I have a minimum age (18) and a maximum age (21). I know that I can do something BETWEEN, but the problem is that I only know years, not dates.

Does anyone have a suggestion on how I can do this?

This is what I am doing now:

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 it does not work 100%.

How can I select only users who are between 18 and 21 years old?

+5
source share
4 answers

:

SELECT * 
FROM rijder 
WHERE geboortedatum BETWEEN 
    CURDATE() - INTERVAL 21 YEAR AND 
    CURDATE() - INTERVAL 18 YEAR

, PHP DATE. , MySQL . , BETWEEN.

+14

::

Select * from table where (DATEDIFF(dob, DATE(NOW())) / 365.25) between 18 and 21
+4
SELECT * FROM rijder 
WHERE geboortedatum 
    between date_add(curdate(), interval -18 year) 
    and date_add(curdate(), interval -21 year)
+2
source

try it

SELECT * FROM rijder WHERE DATEDIFF(NOW(), geboortedatum)/365.25 BETWEEN 18 AND 21
0
source

All Articles