有条件地将复选框值添加到 PHP MySQLi 查询中的最佳方法是什么?

我正在寻找一些关于如何将这些凌乱的代码变成更干净、更高效的建议。


抱歉这不是最干净的代码,但我希望你能理解它。我有 4 个 GET 参数,(P、O、N、C)。


这些 GET 参数是复选框的结果,将具有值 ON 或不会在 URL 字符串中传递。


如果复选框为 ON,我需要附加到 SQL 查询,并在它后面加上一个 OR - 如果后续的 GET 参数也为 ON(以避免最后出现不必要的 OR)。


我猜这个问题的答案是将 GET 参数存储到一个数组中,每个参数都有一个 while 循环?


$select = "SELECT * FROM cif_schedules WHERE tiploc_code = '$t'";

$select .= " AND (";

if($_GET['w'] == "on"){$select .= "cif_schedules.CIF_stp_indicator = 'P' ";}

if($_GET['o'] == "on" && ($_GET['w'] == "on")){$select .=" or ";};

if($_GET['o'] == "on"){$select .= "cif_schedules.CIF_stp_indicator = 'O' ";}

if($_GET['s'] == "on" && ($_GET['o'] == "on" || $_GET['w'] == "on")){$select .=" or ";};

if($_GET['s'] == "on"){$select .= "cif_schedules.CIF_stp_indicator = 'N' ";}

if($_GET['c'] == "on" && ($_GET['s'] == "on" || $_GET['o'] == "on" || $_GET['w'] == "on")){$select .=" or ";};

if($_GET['c'] == "on"){$select .= "cif_schedules.CIF_stp_indicator = 'C' ";}

$select .= ")";

$select .= " AND deleted >= '$maxdate' AND created <= '$maxdate'";

我正在清理用户的输入,所以不要担心安全性等。谢谢


月关宝盒
浏览 144回答 1
1回答

繁星coding

我会制作一个转换数组,将输入值转换为数据库中的值。遍历此数组并构建查询。像这样的东西:// FormValue => DbValue$conversions = ['w' => 'P', 'o' => 'O', 's' => 'N', 'c' => 'C'];$ors = [];foreach($conversions as $input => $value) {&nbsp; &nbsp; // Check if $input is in $_GET and if its value is 'on'&nbsp; &nbsp; if (isset($_GET[$input]) && $_GET[$input] == 'on') {&nbsp; &nbsp; &nbsp; &nbsp; // Push in $ors&nbsp; &nbsp; &nbsp; &nbsp; $ors[] = "cif_schedules.CIF_stp_indicator = '{$value}'";&nbsp; &nbsp; }}因此,您将获得OR数组$ors中的所有内容,您只需内爆并$select在需要时将其添加到:$select = "SELECT * FROM cif_schedules WHERE tiploc_code = '$t'";// Check if there are some ORif (!empty($ors)) {&nbsp; &nbsp; // Add the ORs to the query&nbsp; &nbsp; $select.= ' AND ('.implode(' OR ', $ors).')';}$select .= " AND deleted >= '$maxdate' AND created <= '$maxdate'";
打开App,查看更多内容
随时随地看视频慕课网APP