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

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

mysqli - Remove selected option from dropdown php

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

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

1 Answer

0 votes
by (71.8m points)

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>";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...