【问题标题】:Filter MYSQL query with form options使用表单选项过滤 MYSQL 查询
【发布时间】:2015-12-17 14:26:41
【问题描述】:

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

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

这段代码看起来很难看,即使对我(初学者)来说,感觉也不对,听起来不像是编码方式。

那么,有没有更好更简单的方法来构建这段代码?

【问题讨论】:

  • 您缺少 where 子句“SELECT * FROM solicitacoes WHERE $parametros”
  • 是的,我已经有了,我忘了,对不起!我已经添加了这一行。
  • 发布的答案有任何运气/问题吗?

标签: php mysql select


【解决方案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()WHERE 子句的谓词之间插入and(它会计算出需要多少个,如果有的话)。此外,由于提交 POST 的是您的 HTML 表单,因此您可以确定至少为每个 POST 变量传递了一些值(因此不需要isset())。

【讨论】:

  • 如果未设置$_POST,这将引发警告。索引将是未定义的。您需要issets 或emptys。如果不熟悉,您还应该阅读 SQL 注入。这个答案对 SQL 注入开放(就像 OPs 代码一样)。
【解决方案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 = ?和简历=?和状态=?

? 由驱动程序稍后在进程中填充值。这可以防止用户添加恶意代码来操纵 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 函数并注释掉回显行以查看代码的作用。这就是我确认查询正在按预期构建的方式。

【讨论】:

  • mysqli_stmt_bind_param() 不应该使用所有参数调用一次吗?我不认为它可以像 PDO 的 bindParam() 这样循环调用
  • 嗯,是的,你可能是对的。我认为这种方法有效,但我现在没有看到任何其他文档显示这一点。我会改变它。谢谢。
猜你喜欢
  • 2018-12-05
  • 2013-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-01
相关资源
最近更新 更多