Filter MYSQL query with form options

前端 未结 2 1079
旧时难觅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:49

    Give this a try. From my testing locally (without db) looked right.

    $n_req = 0;
    $_POST['usuario'] = 'test';
    $_POST['resumo'] = 'test2';
    $_POST['status'] = 'test3';
    if (!empty($_POST['usuario'])) {
    $req_usuario = $_POST['usuario'];
    $where[] = " usuario = ? ";
    $params[] = $req_usuario;
    $n_req++;
    }
    if (!empty($_POST['resumo'])) {
    $req_resumo = $_POST['resumo'];
    $where[] = " resumo = ? ";
    $params[] = $req_resumo;
    $n_req++;
    }
    if (!empty($_POST['status'])) {
        $req_status = $_POST['status'];
    $where[] = " status = ? ";
    $params[] = $req_status;
    $n_req++;
    }
    $sql_where = !empty($where) ? ' where ' . implode(' and ', $where) : '';
    echo $sql_where;
    $tot = mysqli_prepare($con, "SELECT * FROM solicitacoes $sql_where");
    if(!empty($params)) {
    //foreach($params as $param) {
    //  mysqli_stmt_bind_param($tot, "s", $param);
        //echo $param;
    //}
    $params = array_merge(array($tot),
                      array(str_repeat('s', count($params))), 
                      array_values($params));
    print_r($params);
    call_user_func_array('mysqli_stmt_bind_param', $params);
    // adapated from https://stackoverflow.com/questions/793471/use-one-bind-param-with-variable-number-of-input-vars and http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli may need to be altered
    }
    echo "SELECT * FROM solicitacoes $sql_where";
    mysqli_execute($tot);
    

    If all three values are populated your query should be

    SELECT * FROM solicitacoes where usuario = ? and resumo = ? and status = ?

    The ? are populated with the values by the driver later in the process. This prevents the user(s) from adding in malicious code to manipulate the SQLs processing.

    https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_Queries.29
    How can I prevent SQL injection in PHP?

    I also didn't see where $funcao was set..

    You can comment out the mysqli functions and decomment out the echo lines to see what the code does. That is how I confirmed queries were being built as expected.

提交回复
热议问题