使用表单选项过滤MYSQL查询

时间:2015-09-21 00:55:35

标签: php mysql select

我有一个包含多个输入的表单,这是我的过滤器。 这是我的代码(不是全部,只是我要解决的部分):

$req_resumo = '';
$req_status = '';
$req_usuario = '';
$n_req = 0;
$parametros = "";

// Checks which fields are filled and increases the number of filters for future usage
if (isset($_POST['usuario']) && $_POST['usuario'] != "") {
    $req_usuario = $_POST['usuario'];
    $n_req++;
}

if (isset($_POST['resumo']) && $_POST['resumo'] != "") {
    $req_resumo = $_POST['resumo'];
    $n_req++;
}

if (isset($_POST['status']) && $_POST['status'] != "") {
    $req_status = $_POST['status'];
    $n_req++;
}

// Then (there is some code between these parts)
if ($n_req > 0 && $funcao != 'usuario') $parametros.= " where ";
if ($req_usuario != "") {
    $parametros.= " usuario = '$req_usuario' ";
    if ($n_req > 1) $parametros.= " and ";
}

if ($req_resumo != "") {
    $parametros.= " resumo = '$req_resumo' ";
    if ($n_req > 1 && ($req_status != "") || ($req_data_inicial != "")) $parametros.= " and ";
}

if ($req_status != "") {
    $parametros.= " status = '$req_status' ";
}

// This will create the query and add the parameters string at the end.
$tot = mysqli_query($con, "SELECT * FROM solicitacoes $parametros");

这段代码看起来很难看,甚至对我来说(begginer),它感觉不对,听起来不像编码方式。

那么,是否有更好,更简单的方法来构建此代码?

2 个答案:

答案 0 :(得分:2)

试一试。从我在本地的测试(没有数据库)看起来是正确的。

$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);

如果填充了所有三个值,则查询应为

  

SELECT * FROM solicitacoes where usuario =?和resumo =?和状态=?

稍后在此过程中,?将由驱动程序填充值。这可以防止用户添加恶意代码来操纵SQL处理。

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?

我也没看到$funcao设置在哪里..

您可以注释掉mysqli函数并取消注释回显行以查看代码的作用。这就是我确认查询按预期构建的方式。

答案 1 :(得分:1)

$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) );
}

我可能没有完全按照要求提供所有逻辑......但是这些想法都在那里。使用implode()and子句的谓词之间插入WHERE(如果有的话,它会计算出需要的谓词数)。此外,由于它是提交POST的HTML表单,因此您可以确定每个POST变量至少传递一些值(因此不需要isset())。