使用PHP填充下拉列表而不重复

时间:2013-04-28 00:47:46

标签: php mysql drop-down-menu

我正在尝试将下拉列表嵌入到更新页面,它工作正常,但我遇到选项选择部分的问题。显示选项时,它也会在列表中复制它。 有没有办法我可以说如果使用记录不再使用它与PHP?

<?php

                        $sql = "SELECT TeamName, TeamID FROM tblTeam";
                        $result = mysql_query($sql);
                        $player_id = $_GET['id'];
                        $current_team = mysql_query("SELECT
                                        tblteam.TeamID,
                                        tblteam.TeamName,
                                        tblplayer.PlayerID,
                                        tblplayer.PlayerTeam,
                                        tblplayer.PlayerName
                                        FROM
                                        tblplayer
                                        INNER JOIN tblteam ON tblplayer.PlayerTeam = tblteam.TeamID
                                        WHERE PlayerID = $player_id LIMIT 1 ");
                        $my_row = mysql_fetch_array($current_team);
                        ?>
                        <select name="TeamName">

                            <option selected value="<?php echo $my_row['TeamID']; ?>"> <?php echo $my_row['TeamName']; ?> </option>
                            <?php
                            while ($row = mysql_fetch_array($result)) {
                                $team_name= $row["TeamName"];
                                $team_id = $row["TeamID"];
                                echo "<option value=\"$team_id\">$team_name</option>";
                            }
                            echo "</select>";
?>

1 个答案:

答案 0 :(得分:2)

如果条件能解决你的问题似乎很简单:

while ($row = mysql_fetch_array($result)) {
    $team_name= $row["TeamName"];
    $team_id = $row["TeamID"];
    if($team_id != $my_row['TeamID']){
        echo "<option value=\"$team_id\">$team_name</option>";
    }
}

此外,在您的示例中,您应该始终清理$ _GET / $ _POST参数:

$player_id = intval($_GET['id']);
如果给定格式不是数字,

Intval将返回0,因此从现在开始您的SQL查询是安全的。