Rajasekar Rajasekar - 2 months ago 8
PHP Question

How to Keep the selected value of the select box after Form POST or GET

Im trying to implement the search feature in my website.

when the search keyword is entered in the textbox, and the category combo is selected, the form will be Posted and the result will be shown on the same page.

what i want is to keep the selected category of the combo by default in the form after posted

For eg., If i select the category 'Automobiles' in the combo and click search, after form submit, the combo should show the automobiles as default selected option. Please help me. Any help will be appreciated

Answer

I assume you get categories from database.

you should try:

<?php

$categories = $rows; //array from database
foreach($rows as $row){
     if($row['name'] == $_POST['category']){
          $isSelected = ' selected="selected"'; // if the option submited in form is as same as this row we add the selected tag
     } else {
          $isSelected = ''; // else we remove any tag
     }
     echo "<option value='".$row['id']."'".$isSelected.">".$row['name']."</option>";
}
?>