Set selected option of select tag & fetch_array

Discussion in 'PHP' started by basketmen, Nov 19, 2014.

  1. #1
    I have this code, there is no selected yet


    I want to set selected option, already tried this in red, but its selected all value



    then tried this in red
    the result is getting error message like this, maybe its still not correct or cant use php code inside it :
    Parse error: syntax error, unexpected T_IF in /home/username/public_html/test.php on line 29




    tried put echo, just for test
    the result is getting error message like this, so event cant print simple echo inside it :
    Parse error: syntax error, unexpected T_ECHO in /home/username/public_html/test.php on line 29



    please help share your knowledge guys, what is the right code to set selected in above code

    GBU for all the answering
     
    basketmen, Nov 19, 2014 IP
  2. PunctRo

    PunctRo Active Member

    Messages:
    102
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    83
    #2
    Something like this should do the trick :

            
    while($datas=mysql_fetch_array($rs)){
           $selected = ($datas['product'] == 'test') ? 'selected' : '';       
           $data .= "<option value='$datas[product]' " . $selected . ">$datas[product]</option>";
    }
    
    PHP:
    Hope it helps !
     
    PunctRo, Nov 19, 2014 IP
    basketmen likes this.
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    And that can also be done within the output (avoiding extra variables), by doing it like this:
       
    while($datas=mysql_fetch_array($rs)) { 
    $data .= "<option value='$datas[product]' " .( ($datas['product'] == 'test') ? 'selected' : '') . ">$datas[product]</option>";
    }
    
    Code (markup):
     
    PoPSiCLe, Nov 19, 2014 IP
    basketmen likes this.
  4. basketmen

    basketmen Well-Known Member

    Messages:
    837
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    130
    #4
    liked, thank you & gbu guys
     
    basketmen, Nov 19, 2014 IP