views:

153

answers:

3

Hello, I have a blogs and questions section on my site that has categories. When a user composes a question or a blog, there is a drop down menu that allows you to choose your category. When you edit either of these you have the option of changing your category via the dropdown. When you go to edit a blog,the category drop down is a standard style dropdown,and I've used <option value="1" <?php if($blog->category == "1"){echo "selected";}?> >Art and Literature</option>to display the previously chosen category. I am picking up where another developer left off, so for the questions one he put the drop down in while loop. Being a newbie I don't know how to "echo selected" in the while loop to make it pull the previously chosen cat.Here is the loop

                       <select name="category">
                            <option value="null">Choose Category</option>
                            <?php
                            $query = "SELECT * FROM `Categories_questions` ORDER BY `CategoryName` ASC";
                            $request = mysql_query($query,$connection);
                            while($result = mysql_fetch_array($request)) {
                                echo "<option value='" . $result['id'] . "'>" . $result['CategoryName'] . "</option>";
                            }
                            ?>

                        </select>
+3  A: 

You can do it the exact same way. Assuming you have the $blog object available where this code is running:

while($result = mysql_fetch_array($request)) {
    $selected = ($result['id']==$blog->category) ? ' selected="selected"' : '';
    echo "<option value='" . $result['id'] . "' ".$selected.">" . $result['CategoryName'] . "</option>";
}
Jage
A: 
 while($result = mysql_fetch_array($request)) {
   $selected = ($result['id'] == $blog->category) ? "selected" : "";
   echo "<option value='" . $result['id'] . "' $selected>" . $result['CategoryName'] . "</option>";
 }

If you don't know what that's doing, it's a ternary operator. Essentialy, it checks if $result['id'] equals the current $blog->category, and if it does then $selected will contain the string "selected". If it doesn't, it just contains an empty string. Then, inside your <option> element, you are either outputting and empty string or "selected".

tj111
A: 

I'd do something like:

while($result = mysql_fetch_array($request)) {
    $value = $result['id'];
    $selected = "";
    if (check_if_selected($value)) {
        $selected = "selected";
    }
    echo "<option value='" . $value . "' " . $selected . ">" .
          $result['CategoryName'] . "</option>";
}
slebetman
Where is "check_if_selected" defined? That isn't a built-in function in php.
Jage