如何在高级搜索中搜索范围日期

时间:2014-07-07 13:00:29

标签: php mysql codeigniter

我使用此功能构建具有许多条件的高级搜索,但是当搜索时,我会陷入一个问题 如何在 - 或(或)条件之间仅使用日期

//发布输入

$pi_num = $this->input->post('pi_num');
$pi_name = $this->input->post('pi_name');
$pi_passport = $this->input->post('pi_passport');
$pi_date_reg = $this->input->post('pi_date_reg');
$pi_date_reg2 = $this->input->post('pi_date_reg2');
$pi_branch_id = $this->input->post('pi_branch_id');
$pi_gender = $this->input->post('pi_gender');
$pi_importance = $this->input->post('pi_importance');

//把它放到数组中     $ conditions = array();

if ($pi_num !== '') {
    $conditions[] = 'pi_num LIKE "' . $pi_num . '"';
}
if ($pi_name !== '') {
    $conditions[] = 'pi_name LIKE "%' . $pi_name . '%"';
}
if ($pi_passport !== '') {
    $conditions[] = 'pi_passport = "' . $pi_passport . '"';
}
if ($pi_date_reg !== '') {
    $conditions[] = 'pi_date_reg = "' . strtotime($pi_date_reg) . '"';
}
if ($pi_date_reg2 !== '') {
    $conditions[] = 'pi_date_reg = "' . strtotime($pi_date_reg2) . '"';
}
if ($pi_gender !== '') {
    $conditions[] = 'pi_gender = "'.$pi_gender.'"';
}
if ($pi_importance !== '') {
    $conditions[] = 'pi_importance = "' . $pi_importance . '"';
}
if ($pi_branch_id !== '') {
    $conditions[] = 'pi_branch_id = "' . $pi_branch_id . '"';
}

然后使用implode函数收集所有内容..但我想使用date..how的另一个查询条件来执行此操作?

$sqlStatement = 'SELECT
            d_branch.*,
            d_patient.*
          FROM  d_patient
            LEFT JOIN d_branch
              ON d_branch.branch_id = d_patient.pi_branch_id WHERE ' . implode(' AND ', $conditions)
;
$result = $this->db->query($sqlStatement);

return $result->result_array();

}

这是查询示例

SELECT d_branch.*, d_patient.* FROM d_patient LEFT JOIN d_branch ON d_branch.branch_id = d_patient.pi_branch_id WHERE pi_num LIKE "555555" AND pi_passport = "333333" AND pi_date_reg = "1404684000" AND pi_date_reg = "1405029600" AND pi_gender = "1" AND pi_importance = "1" AND pi_branch_id = "1443"

2 个答案:

答案 0 :(得分:1)

if ($pi_date_reg !== '') {
  if ($pi_date_reg2 !== '') {
    $conditions[] = '(pi_date_reg BETWEEN "'. $pi_date_reg .'" AND "'. $pi_date_reg2 .'")'; 
  }
  else {
    $conditions[] = 'pi_date_reg >= "'. $pi_date_reg .'"';
  }
}

通过这种方式,第二个日期是可选的,但您可以使用pi_date_reg >= $pi_date_reg搜索所有行的enyway。 确保格式输入日期为yyyy-mm-dd

使用占位符来改善代码安全性:

$conditions = $values = array();
if ($pi_num !== '') {
    $conditions[] = 'pi_num LIKE "%d"';
    $values[] = $pi_num;
}
if ($pi_name !== '') {
    $conditions[] = 'pi_name LIKE "%%s%"';
    $values[] = $pi_name;
}
//...

等等

然后:

$result = $this->db->query($sqlStatement, $values);

答案 1 :(得分:0)

你可以做这样的事情

if ($pi_date_reg !== '' AND $pi_date_reg2 !== '') {
    $conditions[] = "(pi_date_reg  BETWEEN '" . strtotime($pi_date_reg) . "' AND '" . strtotime($pi_date_reg2)."')";
}