Arosha Mudalige Arosha Mudalige - 27 days ago 6
HTML Question

How to get a value of a select input tag with options taken from a database using POST method?

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="doctor">
<?php
$con = mysqli_connect("---","---","---","---") or die("Can't Connect to the Database.");
$sql = mysqli_query($con, "SELECT Title, Name, LastName FROM physician");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"doctor1\">" . $row['Title'].' '.$row['Name'].' '.$row['LastName'] . "</option>";
}

?>
</select>
&nbsp;<input type='submit' value="Filter"><br>
</form>


Above is a form I created. I used POST method. This form has a select input tag and it's options are taken from my database. When form is submitted I need to access the value selected by user using
$_POST['doctor']
function. But it doesn't give me any value. Can anyone help me?

Answer

If the ID for each entry in the "physician" table is stored in a column "PhysicianID", you should try the following code snippet:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <select name="doctor">
        <?php 
            $con = mysqli_connect("---","---","---","---") or die("Can't Connect to the Database.");
            $sql = mysqli_query($con, "SELECT PhysicianID, Title, Name, LastName FROM physician");
            while ($row = $sql->fetch_assoc()){
                echo '<option value="'.$row['PhysicianID'].'">'.$row['Title'].' '.$row['Name'].' '.$row['LastName'].'</option>';
            }
        ?>
    </select>
    &nbsp;<input type='submit' value="Filter"><br>
</form>
Comments