Filter MYSQL query with form options

前端 未结 2 1077
旧时难觅i
旧时难觅i 2020-12-22 10:55

I have a form with multiple inputs which are my filters. This is my code (not all of it, just the part I want to fix):

$req_resumo = \'\';
$req_status = \'\'         


        
2条回答
  •  离开以前
    2020-12-22 11:39

    $predicates = array();
    if ($_POST['usuario'] != "") {
        $predicates[] = "usuario = '{$_POST["usuario"]}'";
    }
    if ($_POST['resumo'] != "") {
        $predicates[] = "resumo = '{$_POST["resumo"]}'"
    }
    if ($_POST['status'] != "") {
        $predicates[] = "status = '{$_POST["status"]}'"
    }
    if (count($predicates) == 0) {
        // handle case when nothing specified in POST
    } else {
        $tot = mysqli_query($con, "SELECT * FROM solicitacoes WHERE "
            . implode(" and ", $predicates) );
    }
    

    I may not have all your logic exactly as required ... but the ideas are there. Use implode() to insert and between the predicates of your WHERE clause (it'll figure out how many are needed, if any). Also, since it is your HTML form that is submitting the POST, you can be certain that at least some value is being passed for each POST variable (so isset() is not required).

提交回复
热议问题