Search code examples
phpsessionloopsdrop-down-menuselected

get selected value of a drop down which is populated with results from an SQL query


So I have a drop down populated with the names based on an SQL query. I want to be able to see which option the user selected before they pressed submit and use this as a variable on a separate php file. I assume I will need to use session variables? I'm a bit lost so any help would be appreciated. I have the following code so far:

<form name="ClientNameForm" id="ClientNameForm" action="ClientDetails.php">
      <input type="text" name="ClientName" id="ClientName" placeholder="Type Service User's name here:" style="width: 200px"/><br/><br/>
      <select name="Name_dropdown" id="name_dropdown" style="width: 200px" >

      <?php
      $ClientName_Query= "SELECT CONCAT(FName, ' ', SName) AS FullName FROM ClientDetails";

      $ClientName_Result= mysql_query($ClientName_Query) or die (mysql_error());                
      while ($row= mysql_fetch_array($ClientName_Result)){

        echo "<option> $row[FullName] </option>";

      }
      ?>
</select><br/><br/>
<input type="submit" name="submit_btn" id="submit_btn" value="Submit"/>
</form>

Solution

  • In your ClientDetails.php file the value will be available using,

    $name = $_POST['Name_dropdown'];
    

    If you need to change a setting in the form document before submitting you can use jQuery. Something like

    $('#name_dropdown').change(function(){
        var option = $(this.options[this.selectedIndex]).val();
    });