我正在努力实现的
目前,我获得了一个包含上千行和10+列的庞大集合,这些列被解析为一个带有PDO的表。之后有必要对表进行过滤,我决定使用PHP进行过滤。
我目前的方法工作得很好,但我不确定它是否在性能上不那么有效,因为有很多else if语句使代码看起来很混乱。
我现在的方法
我得到了一个“筛选表” HTML按钮,它打开了一个弹出窗口,其中有几个按钮(15+左右)在表单中。每个按钮名都有自己的过滤器查询。
然后,我检查单击了哪个按钮,然后将筛选器查询附加到实际的SQL中,该SQL解析了整个表。
我的代码
PHP:
if (isset($_POST['filter_type_pc'])) {
$newFilter = "WHERE type LIKE 'PC%' ORDER BY time_altered DESC";
} else if (isset($_POST['filter_type_mac'])) {
$newFilter = "WHERE type LIKE 'Mac%' ORDER BY time_altered DESC";
} else if (isset($_POST['filter_type_linux'])) {
$newFilter = "WHERE type LIKE 'Linux%' ORDER BY ip DESC";
//...
//there are more 'else if' statements, but I've excluded them to maintain a clean question
//...
} else {
$newFilter = "ORDER BY time_altered DESC";
}
$sql = "SELECT * FROM myTable $newFilter";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();可能是(?)值得注意的是,筛选器查询可以完全不同。我不仅使用WHERE或类子句。
HTML:
<form id="filterTable" name="filter" method="POST" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<h5>Type of device</h5>
<button type="submit" class="btn btn-light filter_button" name="filter_type_pc">PC</button>
<button type="submit" class="btn btn-light filter_button" name="filter_type_mac">Mac</button>
<button type="submit" class="btn btn-light filter_button" name="filter_type_linux">Linux</button>
</form>我的问题
为了进一步澄清,我将提出一个问题。如果有更好和更干净的方法来代替这种else if混乱的话,会是什么呢?我很想听听你的建议,因为我想从中学习,并从已经在工作的代码改进!
发布于 2020-09-10 09:59:27
回答我自己的问题,所以任何未来的访问者,如you,,如果在这个帖子上绊倒了,都可以学到一个简单的解决这个问题的方法。
$filters = array(
"filter_type_pc" => "My SQL query",
"filter_type_mac" => "My SQL query",
"filter_type_linux" => "My SQL query"
);
if (!empty($_POST)) {
$arrayMatch = array_intersect_key($_POST, $filters);
foreach(array_keys($arrayMatch) as $filterName) {
$newFilter = $filters[$filterName];
}
} else {
$newFilter = "ORDER BY time_altered DESC";
};,让我们把它分解:
$_POST请求是否为空,因为我们无法知道使用PHP在DOM中单击了哪个筛选按钮,所以我们只保留空白。$_POST请求中将接受任何内容。如果您有几个请求,我们解决这个byarray_intersect_key,它匹配$_POST和$filters array.$arrayMatch,然后用foreach()和array_keys()循环遍历新创建的数组的匹配键,然后为$filterName.$filterName.将$newFilter定义为$filters数组的值,从而获得数组的值。
编辑:
我想出了一个比上面的解决方案更好的解决方案,而上面的工作方式与前面提到的将来的实现可能会发生冲突。这将修复这个问题,并且只检查包含数组中键的POST请求。
$filters = array(
"filter_type_pc" => "My SQL query",
"filter_type_mac" => "My SQL query",
"filter_type_linux" => "My SQL query"
);
$newFilter = "ORDER BY time_altered DESC";
$arrayMatch = array_intersect_key($_POST, $filters);
foreach(array_keys($arrayMatch) as $filterName) {
if (isset($_POST[$filterName])) {
$newFilter = $filters[$filterName];
}
};https://stackoverflow.com/questions/60278401
复制相似问题