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

167 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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' : '';?>

0
On

You probably have a variable that stores the fields of the employee, right? If you don't, you should, after all you are editing its data, so you should display the current data so you can change what you want.

Let's call this variable $employee.

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

This way, for each territory, you check if it's equal to the employee territory, and if it is, it will add the selected parameter to the tag option.