What I am trying to achieve
I currently got a huge collection with over thousand rows and 10+ columns parsed into a table with PDO. It is necessary to filter the table afterwards and I decided to use PHP to do this.
My current approach works fine, but I am not sure if it's less efficient performance-wise as there are a lot of else if
statements which makes the code looks messy.
My current approach
I got a "Filter Table" HTML button which opens a pop-up with several buttons (15+ or so) inside a form. Each button name has it's own filter query.
I then check which button was clicked and then append the filter query to my actual SQL which parses the whole table.
My code
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();
It might be(?) worth noting that the filter queries can differ completely. I am not only using the WHERE or LIKE clauses.
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>
My question
To clarify even more I am going to ask a question. What would be the better and cleaner approach instead of this else if
mess, if there are any? I am interested in hearing your suggestions as I would like to learn from this and improve from already working code!