使用单个查询从数据库进行多选项搜索

时间:2017-05-26 05:46:28

标签: php jquery mysqli

$data1=$_REQUEST['data1'];
$data2=$_REQUEST['data2'];
$data3=$_REQUEST['data3'];

mysqli_query($conn,"SELECT pu.id, monthname(pu.date_complete) AS Month 
       FROM `pds_user` pu 
     WHERE monthname(pu.date_complete) IN ('".implode("','",$data1)."') 
     AND pu.date_complete IN ('".implode("','",$data2)."') 
     AND Name IN ('".implode("','",$data3)."')
     ORDER BY Month");

如果$ data1为空,该怎么办?

1 个答案:

答案 0 :(得分:1)

使用!empty,然后创建动态where clause

    $where_clause ='where 1=1';

    if(!empty($data1))
    {
       $where_clause .= " And monthname(pu.date_complete) IN ('".implode("','",$data1)."')"; 
    }

    if(!empty($data2))
    {
       $where_clause .= " And pu.date_complete IN ('".implode("','",$data2)."') "; 
    }

    if(!empty($data3))
    {
       $where_clause .= " And Name IN ('".implode("','",$data3)."')"; 
    }

    mysqli_query($conn,"SELECT pu.id, monthname(pu.date_complete) AS Month 
                    FROM `pds_user` pu $where_clause  ORDER BY Month");