Question

am new in php..i am trying to filter my datas from db by using dropdownlist..my code in view form is like

   <?php 
    if(isset($value))
    {
       if($value==1)
      {
      echo"<option value='1' selected>option1</option>
           <option value='0' >option2</option>";    
      } 

      if($value==0)
      {
      echo"<option value='1' >option1</option>
           <option value='0' selected >option2</option>";   
      }    
    }           
    else    
    {
      echo"<option value='1'>option1</option>
           <option value='0'>option2</option>"; 
           $value="";
    }              

  ?>

but if am selecting option1 its working correctly..but when am clicking option2 its filtering the correct datas but its selecting the status only..selected value is status ,ie same as null value...

Was it helpful?

Solution

Simply try replacing your code with this

<select name="status" id="status">
<option value=""><< Select Option >></option>
<option value="1" <?=($status=="1")?"selected":""?>>Active</option>
<option value="0" <?=($status=="0")?"selected":""?>>Inactive</option>           
</select>

Its small and ternary operator is fast then if else conditions.

OTHER TIPS

Before adressing your filtering problem that may need some more explanation I'll suggest to refactor your code to avoid unnecessary conditions and code duplication

This is one way to do it :

<?php $values   = array('Inactive', 'Active') ?>
<?php $selected = (!empty($status)) ? 'selected' : ''  ?>

<?php foreach($values as $value => $label): ?>
    <option value='<?php echo $value ?>' <?php echo $selected ?> ><?php echo $label ?></option>
<?php endforeach ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top