Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

PHP Alternative way to handle records filter in PHP

I have a product page which has filters like search, category, and sort by (name, price).
And my code goes like this.

[CODE lang="php" title="PHP code for filtering results"]if(isset($_GET['category'])){
$products = $cakeOrdering->get_data("SELECT productID, prod_name, price, image FROM products WHERE categoryID = ? ORDER BY productID DESC LIMIT ?, ?", array($_GET['category'], $offset, $results_per_page));
}elseif(isset($_GET['search'])){
$search = $_GET['search'];
$products = $cakeOrdering->get_data("SELECT productID, prod_name, price, image FROM products WHERE prod_name LIKE ? OR prod_desc LIKE ? LIMIT ?, ?", array("%$search%", "%$search%", $offset, $results_per_page));
}elseif(isset($_GET['sort'])){
if($_GET['sort'] == "name"){
$products = $cakeOrdering->get_data("SELECT productID, prod_name, price, image FROM products ORDER BY prod_name LIMIT ?, ?", array($offset, $results_per_page));
}elseif($_GET['sort'] == "price"){
$products = $cakeOrdering->get_data("SELECT productID, prod_name, price, image FROM products ORDER BY price LIMIT ?, ?", array($offset, $results_per_page));
}
}else{
$products = $cakeOrdering->get_data("SELECT productID, prod_name, price, image FROM products ORDER BY productID DESC LIMIT ?, ?", array($offset, $results_per_page));
}[/CODE]

I think it is a bit overkill to have code like this because i have to make sure that I cover all the possible combinations of the filters. Like for example, the user wants to search through specific category, or, sort the search results based on their prices.
Is there a better alternative to do this?
 
Back
Top Bottom