Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a scenario that I have user's edit profile page in which there is a 'Speciality' dropdown and it's option's are getting fetched through While Loop from database table 'speciality'. What I want is to show the Selected option at first in dropdown, for that I have putted following code at top:

<option value=""><?php echo $row2["speciality"];?></option>
             

But problem is again while loop is fetching the same option from the database, so it's getting duplicate, and What I want is to remove selected option from while loop's selected options.

Can Any One help?

Full Code:

<?php
$id = $_GET['id'];
$result = mysqli_query($con, "SELECT * FROM patient WHERE id = $id");
$rows = mysqli_num_rows($result);
$result2 = mysqli_query($con, "SELECT * FROM surgery_team WHERE p_id = $id");
$rows2 = mysqli_num_rows($result2);
while($patient = mysqli_fetch_assoc($result)) {
    $speciality = $patient['speciality'];   
}
}
$result2 = mysqli_query($con,"SELECT * 
                                FROM speciality 
                                WHERE id = $speciality");
$row2 = mysqli_fetch_array($result2);
?>    


<div class="col-6">
    <label class="control-label">Speciality</label>
    <select name="speciality" class="form-control" id="category-dropdown">
    <option value=""><?php echo $row2["speciality"];?></option>
<?php
$result = mysqli_query($con,"SELECT * 
                            FROM speciality 
                            WHERE parent_id = 0");
                    
while($row = mysqli_fetch_array($result)) {
?>
    <option value=""><?php echo $row["speciality"];?></option>
<?php
}
?>
question from:https://stackoverflow.com/questions/65832433/remove-selected-option-from-dropdown-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
678 views
Welcome To Ask or Share your Answers For Others

1 Answer

Instead of throwing 2 copies to the list, just make the one selected the selected item of the dropdown.

<div class="col-6">
    <label class="control-label">Speciality</label>
    <select name="speciality" class="form-control" id="category-dropdown">
    
<?php
$result = mysqli_query($con,"SELECT * 
                            FROM speciality 
                            WHERE parent_id = 0");
                    
while($row = mysqli_fetch_array($result)) {
    $attr = $row2["speciality"] == $row["speciality"] ? "selected='selected'" : '';

    echo "<option $attr value='$row[speciality]'>$row[speciality]</option>";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...