[PHP] Set selected option of select tag & fetch_array

3 replies
I have this code, there is no selected yet
while($datas=mysql_fetch_array($rs)){
$data .= "<option value='$datas[product]' ">$datas[product]</option>";
}


I want to set selected option, already tried this in red, but its selected all value
while($datas=mysql_fetch_array($rs)){
$data .= "<option value='$datas[product]' " . selected . ">$datas[product]</option>";
}



then tried this in red
while($datas=mysql_fetch_array($rs)){
$data .= "<option value='$datas[product]' " . if ($datas['product'] == 'test') { echo 'selected' . ">$datas[product]</option>";
}
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
while($datas=mysql_fetch_array($rs)){
$data .= "<option value='$datas[product]' " . echo 'test'; . ">$datas[product]</option>";
}
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
#option #php #selected #set
  • Profile picture of the author BDazzler
    You want something like this:

    while($datas=mysql_fetch_array($rs)){
    $data .= '<option value="'.$datas['product'].'"';
    if ($datas['product'] == 'test') {
    $data .= "'selectd'";
    }
    $data .= $datas['product']."</option>";
    }
    {{ DiscussionBoard.errors[9681626].message }}
  • while($datas=mysql_fetch_array($rs)){
    $data .= "<option value=\"". $datas[product]."\" ". ($datas['product'] == 'test'? 'selected':"") . ">". $datas[product]. "</option>";
    }

    Note: not tested but should work.
    Signature
    http://premiumwebtechnologies.com

    Affordable, Wordpress plugins & Web Applications
    {{ DiscussionBoard.errors[9681736].message }}
  • Profile picture of the author emptee
    Great answer - just my 2c from past experience (dealing with weird bugs, that aren't immediately obvious!)

    Try to stick with using === and !==, rather than == and !=, when dealing with strings - this will save you from weird stuff in the future liiiiiike...

    if( "0" == "00" )
    {
    //huh? this will be executed...? what?
    }

    if( "0" === "00" )
    {
    //Oh - this won't.. great!
    }

    Cheers,
    Michael

    Originally Posted by premiumwebtechnologies View Post

    while($datas=mysql_fetch_array($rs)){
    $data .= "<option value=\"". $datas[product]."\" ". ($datas['product'] == 'test'? 'selected':"") . ">". $datas[product]. "</option>";
    }

    Note: not tested but should work.
    {{ DiscussionBoard.errors[9682593].message }}

Trending Topics