Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

php - assign selected option value from database

I have a form which contains a dropdown list of countries generated from database. The values are stored in database. There is an option in which user can view or update the valuesinserted. For updating all the form values get fetched from database. What i require is that when form is loaded for updating the selected option of the country dropdown must be that stored in the database. For eg: if from the following dropdown option2 is selected and inserted into database.

 Dropdown: |option1|<selected>
           |option2|
           |option3|

during update it should be like this

 Dropdown: |option1|
           |option2|<selected>
           |option3|

Here is the code i tried.

      $selected = $list["country_country_name"];

     <tr><td>Country</td><td><select onchange="getCountry(this.value);" name="country" id="country" ><?php  foreach( $query as $qry ) { 
     print '<option value="'.$qry["country_country_name"].'"'; 
     if( $qry["country_country_name"] == $selected ) print'selected'; 
     print '>'.$qry["country_country_name"].'</option>'."
";} ?>
     </select></td></tr>
question from:https://stackoverflow.com/questions/65924771/php-form-select-default-value-with-database

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

1 Reply

0 votes
by (71.8m points)

$selected = $list["country_country_name"];

 <tr><td>Country</td>
 <td>
 <select onchange="getCountry(this.value);" name="country" id="country" >
 <?php  foreach( $query as $qry ) { 
    $sel = '';
   if( $qry["country_country_name"] == $selected ) 
    $sel = 'selected="selected"';           

    echo '<option value="'.$qry["country_country_name"].'" '.$sel.'>'.$qry["country_country_name"].'</option>'."
";
    } ?>
    </select>
    <?php echo form_error('country'); ?>
    </td>
 </tr>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...