0

Following is my Php code where all country come from mysql database. It's a user profile area where users can update their country name. But it's not selected (html selected = selected) after he submit his country name. May be it's my $sel variable problem. Can some one fix it ?

<select name="country" class="country"> 
<?php
$sql=mysql_query("select * from country");
while($row=mysql_fetch_array($sql))
{
$id=$row['Code'];
$data=$row['Name'];

    if($data == $country2)
    {
        $sel = 'selected = "selected"';
    }
    else
    {
        $sel = "";
    }

echo '<option value="'.$id.'" $sel>'.$data.'</option>';
}
?>
</select>       

3 Answers 3

4

Variables are not parsed inside of single quotes. You use concatenation for the other variables in your statement, but not $sel...

echo '<option value="'.$id.'"' . $sel . '>'.$data.'</option>';

Or switch to double quotes..

Sign up to request clarification or add additional context in comments.

Comments

1

Please try this:-

<select name="country" class="country"> 
<?php
$sql=mysql_query("select * from country");
while($row=mysql_fetch_array($sql))
{
$id=$row['Code'];
$data=$row['Name'];

    if($data == $country2)
    {
        $sel = 'selected = "selected"';
    }
    else
    {
        $sel = "";
    }

echo '<option value="'.$id.'"' . $sel . '>'.$data.'</option>';
}
?>
</select>       

Comments

0

In PHP, strings in single quotes will not have the variables in their content parsed. $sel will therefore be printed just like that. Either use $sel separately ('<option value="'.$id.'" '.$sel.'>') or use double quotes ("<option value=\"$id\" $sel>").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.