Skip to content
Advertisement

PHP why doesn’t my filtering works as it should be

So, I have to do a web store, where a person can filter the products. I have added the button [pod 300€] and [vsi izdelki]. But now when I click on button [pod 300€] it shows the products which are under 300€ but as well it shows all the products underneath. How to fix that so when I click [pod 300€] it shows only the products under 300€.

the result now

Advertisement

Answer

The problem is that if you get a filter, you make a db-request with the correct filter, but then after, you’re still making the default db-request which fetches all products.

Instead of making multiple db-requests, just make one. You can change the query depending on what filter you get from the client.

Alternative #1 – Dynamically build the query

Something like this:

The upside with this is method is that you easily can add more conditions/filters in the same query.

The downside is that the code gets a bit harder to read.

Alternative #2 – Choose a predefined query

You could have multiple queries defined and choose which to use:

The upside with this method is that it’s very clean and easy to read and follow.

The downside is that you can only have one filter enabled at the same time.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement