Echo Selected base on $_GET value from a dynamic select box

807 views Asked by At

I want to make the select box as selected value from the GET variable. Here is my code:

<select name="suraNo" id="suraNo" required="required">
  <option value="">-Select-</option>
    <?php
      do {  
        ?>
          <option value="<?php echo $row_SuraList['suraNo']?>">
            <?php echo $row_SuraList['suraNo']?>. <?php echo $row_SuraList['suraNameBN']?>
          </option>

          <?php
         } while ($row_SuraList = mysql_fetch_assoc($SuraList));

         $rows = mysql_num_rows($SuraList);
         if($rows > 0) {
           mysql_data_seek($SuraList, 0);
           $row_SuraList = mysql_fetch_assoc($SuraList);
         }
    ?>
</select> 
1

There are 1 answers

0
GRosay On BEST ANSWER

If what you want is to select a value from your list that correspond to your GET param, simply use this:

<option <?php echo ($_GET['yourval'] == $row_SuraList['suraNo'] ? "selected" : null); ?> value="<?php echo $row_SuraList['suraNo']?>"><?php echo $row_SuraList['suraNo']?>. <?php echo $row_SuraList['suraNameBN']?></option>

Also, I suggest you to not close your php balise in your do...while and write your "options" like that:

echo "<option " . ($_GET['yourval'] == $row_SuraList['suraNo'] ? "selected" : null) . " value=\"" . $row_SuraList['suraNo'] . "\">" . $row_SuraList['suraNo'] . "." . $row_SuraList['suraNameBN'] ."</option>";