我有一个包含多个输入的表单,这是我的过滤器.
这是我的代码(不是全部,只是我要解决的部分):
$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),它感觉不对,听起来不像编码方式.
那么,有没有更好,更简单的方法来构建这段代码?
解决方法:
$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子句的谓词之间插入(它将确定需要多少个,如果有的话).此外,由于它是您提交POST的HTML表单,因此您可以确定每个POST变量至少传递一些值(因此不需要isset()).
标签:php,mysql,select
来源: https://codeday.me/bug/20191003/1849398.html