如何在下拉菜单中选择查询结果

时间:2015-01-30 03:07:01

标签: php sql drop-down-menu

我有这个数据库:

  **SBU                **SBU_Users
 *id | *SBU_Name       *users_id | *sbu_id
  1  |  SBU1               1     |   3
     : 
  4  |  SBU4

这是我的代码:

$query = "SELECT sbu.SBU_Name, sbu_users.sbu_id FROM sbu, sbu_users WHERE sbu_users.sbu_id=sbu.id AND sbu_users.users_id=".$users_id."";
        $result = mysql_query($query, $db) or die (mysql_error($db));
            while ($row = mysql_fetch_array($result))
            {
            extract($row);

            }
            echo "<select name=sbuuser>";
            echo "<option value='1' ";if ($sbu_id==1){echo "selected";} else {echo "";}echo ">SBU1</option>";
            echo "<option value='2' ";if ($sbu_id==2){echo "selected";} else {echo "";}echo ">SBU2</option>";
            echo "<option value='3' ";if ($sbu_id==3){echo "selected";} else {echo "";}echo ">SBU3</option>";
            echo "<option value='4' ";if ($sbu_id==4){echo "selected";} else {echo "";}echo ">SBU4</option>";

我在选择正确的SBU_Name时遇到问题,因为我的代码一直在选择最后一个SBU_Name。请帮帮我。

1 个答案:

答案 0 :(得分:0)

也许是这样的?

$query = "SELECT sbu.SBU_Name, sbu_users.sbu_id FROM sbu, sbu_users WHERE sbu_users.sbu_id=sbu.id AND sbu_users.users_id=".$users_id."";
        $result = mysql_query($query, $db) or die (mysql_error($db));

            echo "<select name=sbuuser>";

            while ($row = mysql_fetch_array($result))
            {
            extract($row);

            echo "<option value='1' ";if ($sbu_id==1){echo "selected";} else {echo "";}echo ">SBU1</option>";
            echo "<option value='2' ";if ($sbu_id==2){echo "selected";} else {echo "";}echo ">SBU2</option>";
            echo "<option value='3' ";if ($sbu_id==3){echo "selected";} else {echo "";}echo ">SBU3</option>";
            echo "<option value='4' ";if ($sbu_id==4){echo "selected";} else {echo "";}echo ">SBU4</option>";
            }

            echo "</select>";