如何从数据库中预选当前选定的下拉菜单项? [英] How to make currently selected drop down menu item be preselected from database?

查看:46
本文介绍了如何从数据库中预选当前选定的下拉菜单项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我自己尝试过,但无法正常工作.基本上我正在制作一个编辑页面,可以编辑以前提交的帖子.在这个新页面上,表单预先填充了以前提交的数据.较早选择的其中一项内容是下拉菜单中的类别.我试图让以前的 choden 类别显示为此编辑页面下拉菜单中的默认选择类别.

I tried this on my own but couldn't get it to work right. Basically I am making an edit page where a previously submitted post can be edited. On this new page the form is pre-populated with previously submitted data. One of the things that was chosen earlier was a category from a drop down. I am trying to have that previously choden category show up as the default selected one on this edit page's drop down.

            <select name="categories">
            <?php

                // get the category the post is assigned to
                $query = mysql_query("SELECT category FROM posts");
                while ($row = mysql_fetch_assoc($query)) {
                    $chosenCategory = $row['id'];
                }

                // display a drop down of all categories with the chosen category preselected
                $query = mysql_query("SELECT * FROM categories");
                while ($row = mysql_fetch_assoc($query)) {
                    $catId = $row['id'];
                    $catName = $row['name'];

                    if ($catId == $chosenCategory) {
                        $selected = "selected='selected'";
                    }

                    echo "<option value='$catId' $selected>$catName</option>\n";
                }

            ?>
            </select>

我的代码的问题是它在从指定类别开始的每个选项项上插入 selected='selected'.我需要将它插入到指定的类别选项中.

Problem with my code is it inserts the selected='selected' on every option item starting from the assigned category. I need it to just be inserted to the assigned category option.

例如,假设帖子被分配到名为棒球"的类别,当前输出如下所示:

So for example, suppose the post is assigned to a category called "baseball" here's how the current output looks:

<option value='someid'>Camping</option>
<option value='someid'>Grilling</option>
<option value='someid' selected='selected'>Baseball</option>
<option value='someid' selected='selected'>Swimming</option>
<option value='someid' selected='selected'>Extreme Frisbe</option>
<option value='someid' selected='selected'>Watching TV</option>

它应该在棒球开始和结束的地方,而不是从那里开始并在最后一个菜单项结束,所以自然是预选的那个.

Where it should just start and end at baseball, instead it starts there and ends at the last menu item, so naturally that is the one that is preselected.

如何解决这个问题?

推荐答案

您的代码在各方面都完全正确,除了您忘记在每次循环时重置 $selected.

Your code is completely correct in all ways, except you forgot to reset $selected on every loop.

$selected = '';
if ($catId == $chosenCategory) {
    $selected = "selected='selected'";
}

这篇关于如何从数据库中预选当前选定的下拉菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆