开发者

How to filter results based on age from MySQL database

I have a database setup with user info including name, email, dob, gender, website and other info.

I am trying to implement filter result options for the user page.

The problem is i don't know how to filter by age, since i am storing the age value as a date of birth, i have a php function to get age from it, but how do i go about this.

The filter option is age : 12-24, 25-32, 33-56 (in years)

How do i do like this? select * from users where user.age <= 20 and >= 20 i don't even have a age column, all i have is date of birth.

The filter is stored in session variable $_SESSION['age'] = 12-24 How do i get the first value (12) and the last value (24) from session and later filter so that the age should be greater than 12 and less than 24

开发者_如何学Go

Please help me out.


SELECT * FROM table WHERE DATEDIFF(CURRENT_DATE, dob) >= (12 * 365.25) AND DATEDIFF(CURRENT_DATE, dob) <= (24 * 365.25)


Calendar age: a person born on 2016-02-28 is 0 years old on 2017-02-27 and 1 year old on 2017-02-28. A person born on 2016-02-29 is 0 years old on 2017-02-28 and 1 year old on 2017-03-01. (Leap year).

MySQL's expresssion for this is

   TIMESTAMPDIFF(YEAR, date_of_birth, current_date)

It yields an integer, and handles the truncation and leap years correctly. (The 365.25 division of elapsed days does not necessarily get this right.)


  1. Subtract the birthdate from now to get the age, then compare that.

  2. Use the value of the select (not the text, the value) as a lookup in an array to get the range of ages.


if you want to get both value in diff variable then you should try this.

$sessArr = array();
$sessArr = explode('-',$_SESSION['age']);

now in the array $sessArr you have both value in array $sessArr[0] and $sessArr[1]. You can try this its may helpfull to you.


that should work (haven't tested it')

$_SESSION['age'] = "12-24";

$agroup1 = split($_SESSION['age'],'-');

$min = $agroup1[0]; $max = $agroup1[1];

$query = " select * from users where year(dob) <= year(curdate()) - 12 and year(dob) >= year(curdate()) - 24 ";


SELECT (FLOOR((CURDATE() - `birthfield`) / 10000)) as `age` FROM `tablename` WHERE `age` <= 20 AND ..
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜