Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get dropdown selected value using PDO

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
       } 
       }
       ?>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, e.g.

<option value="<?php echo $output["id"]; ?>" ><?php echo $output["first_name"], $output["last_name"]; ?> 
</option>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading