Skip to content
Advertisement

Fetch database results by choosing dropdown option

I have a small problem with my filtering system I’m creating. I have a dropdown with database categories and one category is “Alle” (english: All) and is chosen by default. This option is not in the database but a separate html option.

This is the filter
.

When I open the filter first I see all my database results (because i have a PHP code to show all results if nothing happens at first) but when I choose a random category and then choose “Alle” again there is just an error.

Here is the error
.

Someone know a script (ajax) and php code to show all results by clicking on “all”.

Here are my codes:

index.php

JavaScript

ajaxdata.php

JavaScript

Thanks

Advertisement

Answer

You need to write an if statement in your PHP to check for this special case – if the category ID is “all” then you must not include the category_id = ... part of the query at all in the SQL, because in that case you actually don’t want any restrictions on that field.

e.g.

JavaScript

N.B. I have used a prepared statement and parameterisation here, instead of concatenating $_POST["category_id"] directly into the SQL string. This will protect your code from both SQL injection attacks and certain kinds of unexpected SQL syntax errors which can arise from the content of the variable data. You can find more examples of writing secure queries here

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