Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all users who are within a certain age range

Tags:

php

select

mysql

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?

like image 642
Rick Weller Avatar asked Jul 11 '12 08:07

Rick Weller


3 Answers

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.

like image 54
Zane Bien Avatar answered Nov 17 '22 23:11

Zane Bien


Try this :::

Select * from table where (DATEDIFF(dob, DATE(NOW())) / 365.25) between 18 and 21
like image 27
Sashi Kant Avatar answered Nov 17 '22 22:11

Sashi Kant


SELECT * FROM rijder 
WHERE geboortedatum 
    between date_add(curdate(), interval -18 year) 
    and date_add(curdate(), interval -21 year)
like image 2
juergen d Avatar answered Nov 17 '22 22:11

juergen d