Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP & MySQLi - Show selected value two time in drop-down list

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>
like image 674
BhavinD. Avatar asked Feb 10 '16 18:02

BhavinD.


People also ask

What PHP stand for?

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.

Is PHP still used?

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.


2 Answers

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.

like image 168
Anant Kumar Singh Avatar answered Nov 03 '22 02:11

Anant Kumar Singh


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>

like image 23
Adam Copley Avatar answered Nov 03 '22 03:11

Adam Copley