Search code examples
phpdrop-down-menumysql-logic

How to set the predefined value for the dropdown while we try to edit the data of a row?


I have created a list of employees with few fields which includes dropdown too. the problem is whenever i select edit option and redirected to the edit page the value in the dropdown is getting set to the first value in the database from which i am querying it. i want to set the value of the dropdown same as the predefined one before editing option was selected i.e if i select a territory to edit and its value was T5 before editing i want the same to be selected not T1 instead the code i am using in the edit page is

 <?php                                          
  $sql = "SELECT DISTINCT `territory` FROM se_ae ";
 ?>
                    <select name="territory">
                    <?php foreach ($dbo->query($sql) as $row) { ?>
                    <option value="<?php echo $row['territory']; ?>">
                     <?php echo $row['territory']; ?></option> 
    <?php }
     ?>

Can anyone help me on this.


Solution

  • As you have saved your value within variable. You can try as

    <?php foreach ($dbo->query($sql) as $row) { ?>
        <option value="<?php echo $row['territory']; ?>" <?php echo ($territory == $row['territory']) ? 'selected' : '';?>>
            <?php echo $row['territory']; ?></option> 
    <?php } ?>
    

    Added <?php echo ($territory == $row['territory']) ? 'selected' : '';?>