0
In my product table, I would like to make some basic filters, such as sort by alphabetical order, price, etc...
The idea is as follows, when the user selects a
option
(does not necessarily need to be an option), change the value of an X variable, also changing the query in my SQL.
Example: (Only for you to understand better)
<form action="" method="POST">
<select>
<option value="a">Ordem A-Z</option>
<option value="z">Ordem Z-A</option>
<option value="preco">Ordem por preços</option>
</select>
</form>
<?php
if (isset($_POST["a"])){
$ordenar= "nome_produto";
}
if (isset($_POST["z"])){
$ordenar= "nome_produto DESC";
}
if (isset($_POST["preco"])){
$ordenar= "valor";
}
// A ideia é mudar o valor diretamente na consulta, ao selecionar algum option...
$sql = "SELECT * FROM produtos ORDER BY $ordenar";
?>
This example, it’s incomplete, it’s just an example, but I think it gave you to understand what I want to do.
- It is possible to do this with pure PHP?
- How would I do something like that that works?
- There is another way more "practical" or more certain than this?
- It would work if I used Jquery?
I thank you for any kind of help, a great day at all.
I believe that the best option would be using jquery ajax, so whenever the option was changed you looked for sql in a separate php file according to the selected option, another thing I noticed is q your <select>...</select> is wrong, "name" is missing" and in your php you would have to call the $_POST according to the "name" and not according to each "value" like you did
– Tales Peres
I thought of this alternative, but for that I would have to put one
button
oftype submit
within theform
Isn’t it? You don’t have the possibility of me doing this without pressing a button? Make the filter just by selecting theoption
...– Samuel Verissimo
the way I passed you wouldn’t need any button, you could use jquery’s own change() to check if <select> was changed and so do ajax
– Tales Peres
<select onchange="document.getElementsByTagName('form')[0].submit()">...</select>
– edson alves
This snippet will send the form when changing the option... It’s not the best way, but it should work
– edson alves
@Maybe you can give me an example in practice? I’m a little layman with js...
– Samuel Verissimo