I created my profile page with show all data in form from MySQL. All data is show rightly on form and also in drop-down list. But the problem is selected value is shows two time in the option list.
Here is the my code:
<select class="form-control" name="country" id="country">
<option value="">Select Country
<?php
//Get country list from Country master
$qry = "select * from country_master";
//Execute query
$result = mysqli_query($conn, $qry);
//Assigned fetched array to $Country
while($country = mysqli_fetch_array($result))
{
echo "<option value='$country[1]'>$country[1]</option>";
//Compare User Country with country list. $row[4] is the country column in user table
if($row[4] == $country[1])
echo "<option value='$country[1]' selected='selected'>$country[1]</option>";
}
?>
</option>
</select>
PHP, originally derived from Personal Home Page Tools, now stands for PHP: Hypertext Preprocessor, which the PHP FAQ describes as a "recursive acronym." PHP executes on the server, while a comparable alternative, JavaScript, executes on the client.
PHP is known to be the most frequently used programming language. According to W3Techs, 78.8% of all websites are using PHP for their server-side.
You need to change your while
code like below:-
while($country = mysqli_fetch_array($result)){
//Compare User Country with country list. $row[4] is the country column in user table
if($row[4] == $country[1]){
echo "<option value='$country[1]' selected='selected'>$country[1]</option>";
}else{
echo "<option value='$country[1]'>$country[1]</option>";
}
}
Note: In your code first option is created and then condition is checked, that's why two times it will show the selected option.
The correct answer to the issue you are facing is provided by A-2-A.
Additionally
You are nesting all of your looped options inside your "Select Country" option. you should remove the last</option>
tag before the </select>
tag and move it after "Select Country" like so:
<option value="">Select Country</option>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With