简体   繁体   English

在mysql,php中搜索年龄范围

[英]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 database but DOB is. 年龄未存储在数据库中,但DOB已存储。 So it calculates that. 因此它计算得出。 I also am using a smarty template. 我也正在使用一个聪明的模板。 mysql_open() is my own function. mysql_open()是我自己的函数。 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. 如果您的数据库中有DOB,并且想查找与年龄范围相匹配的行,那么最简单,最有效的方法就是先将您的最小年龄和最大年龄转换为php中的DOB。 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. 假设DOB是时间戳或日期或较长。

You need get the start and end age parts of $query, and then convert start age and end age to dates of birth. 您需要获取$ query的开始年龄和结束年龄部分,然后将开始年龄和结束年龄转换为出生日期。

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' 应该评估为“ 1980-01-01”和“ 1990-01-01”之间的OR dob之类的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM