PHP mysql查询生成器,显示只是我想要的


PHP mysql Query Builder that displays just what I want

我对PHP比较陌生,我需要一些关于搜索查询的帮助。

我有几个下拉'选择'和一个'复选框组',这将过滤从数据库的搜索使用(…WHERE somethingA = 'somethingA' &&somethingB = 'somethingB'等)

这一切都工作得很好,但问题来了,当我想使它使一些搜索字段不必使用,所以如果'SomethingA'要么被禁用或值='none'那么它只会返回somethingB =' somethingB '。

我试过使用OR而不是AND,但如果它们是真的,则返回两个值,而不是真正过滤它。

我最初的解决方案是使用if…else语句来定义查询,例如:

$query = "SELECT * FROM table";        
$results = $con->query("$query $where $QueryA $QueryB $QueryC");
if($_GET['SomethingA'] == "none" && $_GET['SomethingB'] == "none" && $_GET['SomethingC'] == "none"){
$where = ""
$QueryA = ""
$QueryB = ""
$QueryC = "ORDER by ID" //if all search field is 'none' then get all results
}elseif($_GET['SomethingB'] == "none" && $_GET['SomethingC'] == "none"){
$where = "WHERE"
$QueryA = "SomethingA = '{SomethingA}'" //only use A filter one field
$QueryB = ""
$QueryC = "" 
}elseif($_GET['SomethingA'] == "none" && $_GET['SomethingC'] == "none"){
$where = "WHERE"
$QueryA = ""
$QueryB = "SomethingB = '{SomethingB}'" //only use B filter one field
$QueryC = "" 
.....

它可以工作,但你已经可以看到这个问题,如果我想交叉矩阵所有条件,它变得非常冗长和令人困惑。所以我的问题是,是否有更好的方法来做到这一点,例如,使值='none'返回所有结果?

我四处寻找,从很多角度攻击它,但找不到解决方案。也许javascript能帮上忙,但我不是最擅长的。

thanks in advance

这个问题不太清楚,但请仔细研究一下。这应该有帮助。

$query="SELECT * FROM table WHERE";
$query_link = " AND ";
$isASet=false;
$isBSet=false;
$isCSet=false;
if(strcmp($_GET['SomethingA'],"none") != 0){
    $query.=" column = {$_GET['SomethingA']}";
    //set this to true for later if statements
    $isASet=true;
}

if(strcmp($_GET['SomethingB'],"none") != 0){
    //check if A has been set, if yes include an AND
    if($isASet){
        $query.=$query_link;
    }
    //include this one as usual
    $query.=" column = {$_GET['SomethingB']}";
    $isBSet=true;
}
if(strcmp($_GET['SomethingC'],"none") != 0){
    //check if A or B has been set, if yes include an AND
    if($isASet || $isBSet){
        $query.=$query_link;
    }
    //include this as usual
    $query.=" column = {$_GET['SomethingC']}";
}
//run query and collect result
$result = $connection->query($query);