我想显示按WHERE
子句过滤的数据。我已经应用了一些变量来代替条件值,现在如果没有应用条件,如何获取数据。我试过但是它。它是有效的,如果给出了值,但如果没有给出值则它不起作用。
该怎么办?
它有3个过滤器。如果选择日期,则应按给定日期显示数据。如果选择源,它应该再次显示给定日期和给定源的数据。像这样,它应该工作。
$date_from = NULL; //the value will be given if the user selects the date range
$date_to = NULL;
$src_id = NULL; // this value will be given if the user wants data from specific source
$gndr_id = NULL; // if user want data by gender
$leadSql = "SELECT
lead.id as lead_id
, lead.name as lead_name
, lead.phone as lead_phone
, lead.email as lead_email
, gender.name as lead_gender
, treatment.name as treatment_name
, lead.date as lead_date
, source.name as source_name
, status.name as status_name
, lead.remark as lead_remark
FROM lead
join treatment on treatment.id = lead.treatment_id
join gender on gender.id = lead.gender_id
join source on source.id = lead.source_id
join status on status.id = lead.status_id
where (lead.date BETWEEN $date_from and $date_to) and
(lead.source_id = $src_id ) and (lead.gender_id = $gndr_id)
ORDER BY lead_date DESC";
请建议我一些方法。
答案 0 :(得分:1)
就我的知识延伸而言,你需要在一个condictional语句中包含整个WHERE行,以说明值是否存在,如果不忽略它,则应用WHERE子句。
if($date_from != NULL && $date_to != NULL .....){
$where_clause = "where (lead.date BETWEEN $date_from and $date_to) and
(lead.source_id = $src_id ) and (lead.gender_id = $gndr_id)";
} else{
$where_clause ="";
}
$leadSql = "SELECT
lead.id as lead_id
, lead.name as lead_name
, lead.phone as lead_phone
, lead.email as lead_email
, gender.name as lead_gender
, treatment.name as treatment_name
, lead.date as lead_date
, source.name as source_name
, status.name as status_name
, lead.remark as lead_remark
FROM lead
join treatment on treatment.id = lead.treatment_id
join gender on gender.id = lead.gender_id
join source on source.id = lead.source_id
join status on status.id = lead.status_id
".$where_clause."
ORDER BY lead_date DESC";
您可以根据需要调整if / else。这是最简单的解决方案。 您可以为每个变量编写一个条件语句,并在最后将它们连接在一起。
$where = [];
$where_clause = '';
if ($date_from && $date_to) {
$where[] = "(lead.date BETWEEN $date_from and $date_to)";
}
if ($src_id) {
$where[] = "(lead.source_id = $src_id )";
}
if ($gndr_id) {
$where[] = "(lead.gender_id = $gndr_id)";
}
if (count($where)) {
$where_clause = 'WHERE ' . implode(' AND ', $where);
}