I'm trying to get the id of the selected value when I click on the submit button, but it only gives me one id even if I select another value. Thanks in advance.
$sql = "SELECT first_name, last_name, id FROM ea_users where id_roles=2";
try{
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->query($sql);
$results=$stmt->fetchAll();
if($stmt === false){
die("Erreur");
}
}catch (PDOException $e){
echo $e->getMessage();
}
?>
<div class="container mt-5">
<form action="" method="post" class="mb-3">
<div class="select-block">
<select name="proxim">
<option value="" disabled selected>Choisir votre Proxim'IT</option>
<?php foreach ($results as $output){?>
<option><?php echo $output["first_name"], $output["last_name"]; ?>
</option>
<?php } ?>
</select>
</div>
<input type="submit" name="submit" vlaue="Choisir votre Proxim'IT">
</form>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['proxim'])) {
echo $output["id"];
?>
<?php
}
}
?>
You're echoing the ID from the (last row of) data from the DB query, not the value the user selected.
Replace
echo $output["id"];
with
echo $_POST["proxim"];
Note that since your <option>
s don't have a value
attribute, it will output the text within the tags instead (the first and last names, in this case).
If you want the ID to be passed back to PHP instead when the form is submitted, then set that as the value of each option, eg
<option value="<?php echo $output["id"]; ?>" ><?php echo $output["first_name"], $output["last_name"]; ?>
</option>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.