正确的搜索数据

时间:2018-09-12 10:55:27

标签: php sql

我已经编写了用于搜索表数据的代码。我提供多列搜索。但是当我只搜索单列时,时间结果不正确。 屏幕截图:

enter image description here

查询是:-

SELECT
    * 
FROM
    file 
WHERE
    letter = "daak" 
    OR department = "" 
    OR officer = ""
    OR DATE BETWEEN "" AND "" 
ORDER BY
    DATE

当我搜索daak但它显示所有字母

{
 $condition = 'letter ="'.$letter.'" or department = "'.$dept.'" or officer = "'.$officer.'"or date between "'.$fdate.'" and "'.$todate.'" order by date';
          $result =$qgen->select('file','*',$condition);
}

2 个答案:

答案 0 :(得分:0)

我认为您需要在查询中使用 STR_TO_DATE mysql内置函数:

SELECT
    * 
FROM
    file 
WHERE
    letter = 'daak'
    OR department = '' 
    OR officer = ''
    OR DATE BETWEEN STR_TO_DATE('10/09/2018','%d/%m/%Y')AND STR_TO_DATE('12/09/2018','%d/%m/%Y') 
ORDER BY
    DATE

在您的php代码中:

$condition = 'letter ="'.$letter.'" or department = "'.$dept.'" or officer = "'.$officer.'"or date between "STR_TO_DATE('.$fdate.', '%d/%m/%Y')" and "STR_TO_DATE('.$todate.', '%d/%m/%Y')" order by date';
          $result =$qgen->select('file','*',$condition);

答案 1 :(得分:-1)

如果您只想获得满足所有条件的行,则使用“ and”,而不是“ or”

  • “ A和B”的意思是“仅行,其中A和B也不行。”
  • “ A或B”表示“ B的所有行以及A的所有行”

所以您的查询应该是

select * from file where letter ="daak" AND department = "" AND officer
= "" AND date between "" and "" order by date

如果要忽略空的输入字段,则类似

{

 $condArray = array();

 if(trim($letter)) $condArray[] = 'letter = "'.$letter.'"';
 if(trim($dept)) $condArray[] = 'department = "'.$dept.'"';
 if(trim($officer)) $condArray[] = 'officer = "'.$officer.'"'
 if(trim($fdate) or trim($todate)) $condArray[] = 'date between "'.$fdate.'" and "'.$todate.'"';

 $condition = implode(' AND ', $condArray).' order by date';

 $result =$qgen->select('file','*',$condition);
}