Search age range in mysql, php
Hey guys, I need to make a function so that it will search an age range in this function
function search($query) {
$query = mysql_escape_string($query);
$connection = mysql_open();
$statement = "select ID, UserName, Gender, USERDOB,DATEDIFF(USERDOB,now()) from Users ";
if (!empty($query)) {
$statement .= "where FirstName like '%$query%' " .
"or LastName like '%$query%' " .
"or UserName like '%$query%' " .
"or Gender like '%$query%' ";
}
$statement .= "order by id ";
$result = @ mysql_query($statement, $connection)
or showerror();
$users = array();
while ($user = mysql_fetch_array($result)) {
$user[4] = floor($user[4]/-1/364.25);
$users[] = $user;
}
// Close connection and return resulting array
mysql_close($connection)
or showerror();
return $users;
}
This is the function for search. But it also makes it possible to view a persons age. Age is not stored in the databas开发者_如何学运维e but DOB is. So it calculates that. I also am using a smarty template. mysql_open() is my own function. I figure I need to find a way to get age into the query and do some thing with range...
anyway quite lost, any ideas?
If you have DOB in the database and you want to find rows that match an age range the simplest and most efficient thing to do is convert your min age and your max age into DOBs in your php first. Then your query would be something like:
SELECT * FROM USERS WHERE DOB > MIN_DOB AND DOB <= MAX_DOB;
assuming DOB is a timestamp or date or long.
You need get the start and end age parts of $query, and then convert start age and end age to dates of birth.
You can then add
"OR dob BETWEEN '%$startdob%' AND '%$enddob%'"
which should evaluate to something like OR dob BETWEEN '1980-01-01' AND '1990-01-01'
精彩评论