How to echo selected country from the table in a combobox. the combobox is having list of many country. eg. <select> <option>country1</option> <option>country2</option> <option>country3</option> </select> if in table, country2 is stored . Then how to echo country2 as default selected?
<select> <option>country1</option> <option selected="selected">country2</option> <option>country3</option> <option>country4</option> </select> Hope this helps.
Heres a little example I whipped to demonstrate how to do this. <select name="country"> <?php echo ($row['country'] == 'england') ? '<option value="england" selected="selected">England</option>' : '<option value="england">England</option>'; ?> <option value="ireland">Ireland</option> </select> PHP: You can either do so using ternary (like the above) or using if statement/s.
I can do it by: <select> <option <? if($row[country]=="country1" echo "selected"; ?>>country1</option> <option <? if($row[country]=="country2" echo "selected"; ?>>country2</option> <option <? if($row[country]=="country3" echo "selected"; ?>>country3</option> </select> Is there any other shortcut. Coz if there is 500 country i have to echo it for 500 times. I think this is not good tecknique
You can store all the country names in a database or an array and then simply loop through all of them. That way you only have to write the code once.
Hi! Try This Method. Script Not Tested. <?php $countries = ' <select> <option>country1</option> <option>country2</option> <option>country3</option> <option>country4</option> </select> '; $row = $row["country"]; print str_replace(">".$row, " selected='selected'>".$row, $countries); ?>