views:

37

answers:

2

I'm using a form where the user can edit an entry. Everything is populating and all is well with the exception that I can't get the drop down to show the project that they've already assigned the image to.

$project_qry = "SELECT * from projects ORDER BY title ASC";
$project_res = mysql_query($project_qry);

$project_drop = "<select name=\"project_id\">\n";
while ($row = mysql_fetch_array($project_res))
    {
    if ($project_id == $row[title])
        {
            $project_drop .= "<option value=\"$row[id]\" selected>$row[title]</option>\n";
        }
    else
        {
            $project_drop .= "<option value=\"$row[id]\">$row[title]</option>\n";
        }
}
$project_drop .= "</select>\n";

I'm sure it's something devilishly simple but I'm stumped.

+3  A: 
{
    if ($project_id == $row[id])
        {
            $project_drop .= "<option value=\"$row[id]\" selected=\"selected\">$row[title]</option>\n";
        }
    else
        {
            $project_drop .= "<option value=\"$row[id]\">$row[title]</option>\n";
        }
}

You need to compare the value and not the title. It is the value that gets posted ($_POST)

selected="selected" makes it XHTML compliant.

bigstylee
To add to this answer, you should always quote the associative index like so: $row['id']. Also you should escape your arrays in strings with curly braces: $s = "{$row['id']}";
webbiedave
Quoting array keys is not necessary in double-quoted strings. PHP assumes it's a string key and acts accordingly. Curly brace notation is only necessary if you're outputting a multi-dimensional array value, or absolutely have to use the quoted key syntax.
Marc B
Awesome additions to the answer!
86Stang
A: 

bigstylee answered correctly. I also recommend to separate the values of the array and your string:

$project_drop .= "<option value='". $row['id'] ."'>".$row['title']."</option>";

Also drop \n. Outputting \n won't generate a line break in the browser. And it is unnecessary.

Kel
I use \n in my code as well. The resulting html is formatted better which helps in debugging sometimes, especially when you have a large number of options in a select.
webbiedave
just a small fix: put quotes (apostrophe ') around value ... "<option value='". $row['id'] ."'>"
dar7yl
oops, thanks dar7.@webbiedave: thanks for your input. How does the DOM tree react to it?
Kel