Search age range in mysql, php

情到浓时终转凉″ 提交于 2019-12-25 10:55:10

问题


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 database 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?


回答1:


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.




回答2:


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'



来源:https://stackoverflow.com/questions/5611178/search-age-range-in-mysql-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!