Home » Php » sql – Clean and efficient way of sorting table from a form with PHP

sql – Clean and efficient way of sorting table from a form with PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

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 sort 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 “Sort Table” HTML button which opens a pop-up with several buttons (15+ or so) inside a form. Each button has it’s own sorting query.

I then check which button was clicked and then append the sorting query to my actual SQL which parses the whole table.

My code

PHP:

if (isset($_POST['sort_type_pc'])) {
    $new_sort = "WHERE type LIKE 'PC%' ORDER BY time_altered DESC";
} else if (isset($_POST['sort_type_mac'])) {
    $new_sort = "WHERE type LIKE 'Mac%' ORDER BY time_altered DESC";
} else if (isset($_POST['sort_type_linux'])) {
    $new_sort = "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 {
    $new_sort = "ORDER BY time_altered DESC";
}

$sql = "SELECT * FROM myTable $new_sort";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

It might be(?) worth noting that the sorting queries can differ completely. I am not only using the WHERE or LIKE clauses.

HTML:

<form id="sortTable" name="sort" method="POST" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
    <h5>Type of device</h5>
    <button type="submit" class="btn btn-light sort_button" name="sort_type_pc">PC</button>
    <button type="submit" class="btn btn-light sort_button" name="sort_type_mac">Mac</button>
    <button type="submit" class="btn btn-light sort_button" name="sort_type_linux">Linux</button>
</form>

What I’ve tried & my question

I’ve looked into a few possible methods that could have been a nicer approach. I was wondering if there was some way I could take use of the switch statement and store all the variables in an array.

Turns out that’s not possible :/

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!

How to&Answers: