How to set the selected option (from database) of <select> tag in PHP

```I have a drop-down in html which is being rendered from php template. I can edit drop-down choice which takes usernames from DB, but how make it “selected” (what I have choose before) before editing?

<?php $conn = new mysqli($servername, $username, $password, $dbname) or die ('Cannot connect to db');
        $result = $conn->query("select username from users");
    echo "<html>";
    echo "<body>";
    echo "<select name='workers'>";
    while ($row = $result->fetch_assoc()) {
        unset($username);
        $username = $row['username'];
        echo '<option value=" '.$username.'"  >'.$username.'</option>';
    }
    echo "</select>";
    echo "</body>";
    echo "</html>";
?>

Hi balabam166 welcome to the forum

I’ve done what I think you’re looking to do before.

I set a variable

$select_attribute = ''; 

Then inside a conditional I assign the string to replace the empty string. eg.

if ( $some_variable === $some_value ) { 
  $select_attribute = 'selected'; 
} 

Then in the line that generates the option tag

echo '<option value=" '.$username.'" '. $select_attribute . ' >'.$username.'</option>';

The sometimes tricky part is figuring out where to put the variable declaration and assignment if conditional. Give it a try and post back on how you do.

thank you for your reply, but this still not working properly.
I don’t understand why but this one always selected last option ( not the one i choose before). the same is with code :

echo '<option value="'.$username.'" selected>'.$username.'</option>';

Yes, this problem sounds like the “tricky part” I mentioned.
In relation to the while loop, where did you put the declaration and conditional?

Post the code * and I’ll be able to help.

* as below vvv

text, text text then three backticks on their own line
```
code here
```
more text here

text, text text then three backticks on their own line

code here 

more text here

first operation

<form action="process.php" method="POST">
								
Task:
<input type="text" name="task" style="width:400px;font-size:14pt;"
								 value="<? echo $form->value("task");?>"/><br><?echo $form->error("task");?>
								</p>
								Add task for:
<?php
$conn = new mysqli('', '', '', ') 
or die ('Cannot connect to db');
    $result = $conn->query("select username from users");
echo "<html>";
    echo "<body>";
    echo "<select name='worker'>";
   $select_attribute = '';
           while ($row = $result->fetch_assoc()) {
                  unset($username);
                  $username = $row['username']; 
  echo '<option value=" '.$username.' ">'.$username.'</option>';
}
    echo "</select>";
    echo "</body>";
    echo "</html>";
?> </form>	

Process


function procNewEntry() {
        global $session, $form;


if ( $some_variable === $some_value ) { 
  $select_attribute = 'selected'; 
}
        $retval = $session->newEntry($_POST['task'], $_POST['worker]);

        /* task registration successful */
        if ($retval == 0) {
            $_SESSION['regsuccess'] = true;
            header("Location: " . $session->referrer);
        }
        /* Error found with form */ else if ($retval == 1) {
            $_SESSION['value_array'] = $_POST;
            $_SESSION['error_array'] = $form->getErrorArray();
            header("Location: " . $session->referrer);
        }
        /* Registration attempt failed */ else if ($retval == 2) {
            $_SESSION['regsuccess'] = false;
            header("Location: " . $session->referrer);
        }
    }

Edit operation


<form action="admin/adminprocess.php" style="text-align:left;" method="POST">

 task: <br>

> <input type="text" name="task" value="<?php echo $task; ?>"><br>

> </p>

> Add task: <br>
> <?php
> $conn = new mysqli() 
> or die ('Cannot connect to db');
>     $result = $conn->query("select username from users");
> 	
>     echo "<html>";
>     echo "<body>";
>     echo "<select name='worker'>";
> 	
>     while ($row = $result->fetch_assoc()) {
>                   unset($username);
>                   $username = $row['username']; 
> 				 
>                   echo '<option value=" '.$username.'" '. $select_attribute . ' >'.$username.'</option>';
> }
>     echo "</select>";
>     echo "</body>";
>     echo "</html>";
> 	
> ?>

adminprocess

function procUpdateEntry() {
global $session, $database;

  	$id = $_POST['subedit'];
  	$task = $_POST['task'];
  	$worker = $_POST['worker'];
  	/* Update details */
  	$q = "UPDATE " . TBL_TASKS . " SET task = '$task', worker = '$worker' WHERE id = '$id'";
  	$database->query($q);
  	header("Location: ../operacija2.php?s=ok");
  }

Hope you understand

Much of that doesn’t pertain to what I had in mind.

The “some_variable” and “some_value” that assigns a value to “select_attribute” would not be inside the procNewEntry function unless you wanted to pass the “select_attribute” variable to where it’s needed in some way. IMHO, doing so would make things uneccessarily more complex than needs be. Much easier to have the conditional inside the while loop that generates the select options.

Also, “some_variable” and “some_value” are my way of indicating that “something goes there” and are not meant to be used in the actual code. Sorry if this confused you, I have a habit of assuming others will understand my eccentricities.

So what should those be? It depends on what criteria you want to use to determine which select option, if any, you want to be as the “selected”. I do not know this, it could be the first, the last, one that has a specific id or name etc.

Which select option do you want to be the default selected option?

there is no default option, option depend for which user I add a task.
After I add task for him I want to edit it. And editing is working but option of workers is not selected.

I suspect that’s because you put “selected” on every option, so the browser just picks the most-recently-selected, which is the last one.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.