0

I am pretty new to PHP and am having a question about dropdown lists. I am trying to get the list to pull from the database and populate the value when a user edits a form but it is not currently working. There are a few examples of this exact same thing on here but I can't quite get it working, it is likely a syntax error on my end...

Here is my code:

echo '<p><label>Is this project targeted toward?</label><select name="proj_targ_tow"><option value="Select...">Select...</option><option value="National Site">National Site</option><option="Local Site">Local Site</option><option value="Regional Site">Regional Site</option><option value="Other">Other</option></select></p>';

And here is the logic to populate the value from the database, the row I am trying to pull from is 'proj_targ_tow'...

    $typesArray = array ( 'Select..', 'National Site', 'Local Site', 'Regional Site', 'Other' );
$selectedType = '';
echo 'as;ldfjas;lfmawoiealknfsliu2047a   ' . $row['proj_targ_tow'] . '<br />';
foreach($typesArray as $value){
    if($value == $row['proj_targ_tow']) {
        $selectedType = 'selected="selected"';
} 
echo '<option value="' . $value . '" ' . $selectedType . '>' . $value . '</option>';
}

Can any of you coding gods out there help me out?

4
  • aint no gods around mate Commented May 4, 2012 at 14:50
  • What is the value of $row['proj_targ_tow']? Commented May 4, 2012 at 14:51
  • Also, I'm not sure if you intended it, but make sure you do: $selectedType = '' inside the foreach loop (at the start). Commented May 4, 2012 at 14:55
  • @TusharDhoot - when I echo it out it returns the value from the database (National Site)... Commented May 4, 2012 at 14:55

1 Answer 1

2

It looks to me like the $value in your echo statement is out of scope... what happens when you do this?

$typesArray = array ( 'Select..', 'National Site', 'Local Site', 'Regional Site', 'Other' );

foreach($typesArray as $value){
    $selectedType = '';

    if($value == $row['proj_targ_tow'])
        $selectedType = 'selected="selected"';

    echo '<option value="' . $value . '" ' . $selectedType . '>' . $value . '</option>';
} 
Sign up to request clarification or add additional context in comments.

2 Comments

this is pretty much it, except for I needed an else to populate all the other values that are NOT selected. Thanks for your help!!!
I'm happy to have been of assistance.

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.