I have the following code in HTML and PHP:
<form autocomplete="off" action="" method="post">
<select>
<?php $sql = "SELECT id, anio FROM anios order by anio";
$anios= conexion($sql);
$data["titulo"] = "anios";
$data["anios"] = $anios;
foreach($data["anios"]as $dato){
$id= $dato["id"];
$anio= $dato["anio"];
?>
<option name="<?php echo $id;?>" id="<?php echo $id;?>" value="<?php echo $anio;?>">
<?php echo $anio;?></option>
<?php
} ?>
</select>
<button type="submit" name="filtro" class="btn btn-primary" style='font-
size:20px;color:white;'>Filtrar</button>
</form>
El año que seleccionaste fue: <?php echo $anio; ?> y el ID del año es: <?php echo $id; ?>
What happens when you press "Filter" is the following:
As can be seen in the image, even though I select another year, the same 2021 is always displayed. How can I solve this problem? Thank you very much in advance!
You
name
have to put it in the tagselect
once, and when you submit the form the value of the 'option` that is currently selected will be sent.Something like that:
And when picking up the post:
If you are interested in the year and the dynamic id, you can put
value
both values in it with a separator and then useexplode()
.For example, when you create the
option
:And when retrieving the post:
If you are also interested in the id or other more complex things, consider retrieving it dynamically on the client side and to communicate between client and server it is better to use Ajax or the new Javascript Fetch API, so you can assign more things, such as the
id
, using listening for events and sending a set of dynamic data to the server, plus Ajax and Fetch both allow you to fetch and fetch data from both contexts without reloading the page.I have also allowed myself to clean up your code a bit, putting all the PHP code in a single block. The constant opening and closing of blocks produces code that is unreadable and difficult to debug/parse.