duan35557593 2010-10-03 17:00
浏览 15
已采纳

PHP:过滤:计算生日年龄,BETWEEN xx和xx

After some research and little afford from myself I got this:

     $query .= "SELECT * FROM users WHERE birthday < SUBDATE(NOW(), INTERVAL BETWEEN $min AND $max YEAR)";

Although this doesn't work.

Users birthdays are stored in: 1991-01-01 in the birthday column. I have two fields in my form, that you can enter numbers in. example, 18 and 22.

then it will show all users that has the age between 18 and 22 ( 18,19,20,21,22).

^ And that is what im trying to filter out, with the query. But ive done something wrong, and maybe you cant do BETWEEN in INTERVAL, or what is wrong?

Im getting:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BETWEEN 17 AND 21 YEAR)' at line 1
  • 写回答

3条回答 默认 最新

  • duanbushi1867 2010-10-03 17:08
    关注

    But ive done something wrong, and maybe you cant do BETWEEN in INTERVAL, or what is wrong?

    Exactly - BETWEEN is a boolean operator, which means it returns a boolean value (true or false), and INTERVAL wants an integer.

    WHERE birthday
      BETWEEN SUBDATE(NOW(), INTERVAL $max YEAR)
          AND SUBDATE(NOW(), INTERVAL $min YEAR)
    

    and a warning - you better have those variables properly escaped (with mysql_escape_string). Bobby Tables!

    Also note that: using NOW() means that you would be including people born 17 years 23 hours ago, but excluding people born 18 years and 1 hour ago. That is not typically what we mean by "birthday" - you would better use TODAY() than NOW().

    However, with TODAY(), there is another issue: BETWEEN is inclusive; thus, between 18 and 20, you do not have 2 years, but 2 years and a day. Overcome this by splitting BETWEEN up and doing normal comparison (birthday > ... AND birthday <= ...)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图