How can the PHP code be modified to ensure that all options in the select field are displayed correctly?

The issue with displaying all options in the select field correctly can be solved by ensuring that the value attribute of each option matches the selected value in the database. This can be done by checking if the value of each option matches the value retrieved from the database, and adding the "selected" attribute to the option that matches.

<select name="category">
    <?php
    $categories = array("Option 1", "Option 2", "Option 3"); // Example array of options
    
    foreach($categories as $category) {
        if($category == $selectedCategory) {
            echo "<option value='$category' selected>$category</option>";
        } else {
            echo "<option value='$category'>$category</option>";
        }
    }
    ?>
</select>