php搜索日期字符串

标签 php mysql date

我得到了一些 DOB 格式 yyyy-mm-dd 的客户列表。
我如何通过出生日期搜索客户,即使我先输入年或月或日期,它也会显示结果。

目前,我需要使用格式 yyyy-mm-dd 来搜索它们。

$result = $db->query("SELECT f_name, l_name, dob, email FROM user WHERE dob LIKE'$keyword%' OR f_name LIKE '$keyword%' OR l_name LIKE '$keyword%' LIMIT 100")

if($result) {
  if($db->affected_rows()!= 0){

     // echo the result

  }
}

最佳答案

您可以使用 YEAR()MONTH()DAY() 来代替 LIKE比较.确保您已经正确转义了 $keyword...

$result = $db->query("
  SELECT f_name, l_name, dob, email
  FROM user 
  WHERE
    // The year, month, or day can be an exact match (note parentheses)
    (YEAR(dob) = '$keyword' OR MONTH(dob) = '$keyword' OR DAY(dob) = '$keyword')
    // Or the full yyyy-mm-dd date can be an exact match
    OR DATE(dob) = '$keyword'
    // OR UK date format
    OR DATE(dob) = STR_TO_DATE('$keyword', '%d/%m/%y')
    // or the rest of your conditions...
    OR f_name LIKE '$keyword%' OR l_name LIKE '$keyword%' LIMIT 100"
);

编辑:在整数日期组件周围添加引号,以避免搜索字符串而不是数字时出现语法错误。

关于php搜索日期字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8489255/

相关文章:

php - 当外部存储库不再存在时,Composer/Laravel 从现有文件安装包

php - 如何使用 PHP 获取 MySQL 数据库表中的最后一条记录?

php - CI Ion Auth,查看是否有不同用户登录

PHP 日期 : week numbers for 2015/2016

PHP Header 向上移动一个目录?

php - 如何防止嵌套函数调用?

php - 正则表达式中的 StackOverflow 样式 A Href 自动链接

php - 将 yii 默认用户名字段更改为电子邮件字段以进行登录

sql - 查找日期范围内存在的天数

java - 当存在 JsonSerializer<Timestamp>() 时,JsonSerializer<Date>() 不适用于 java.util.Date 字段