php查询mysql表单,php – 使用表单选项过滤MYSQL查询

我有一个包含多个输入的表单,这是我的过滤器.

这是我的代码(不是全部,只是我要解决的部分):

$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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值