douyuqing_12345 2013-04-28 00:47
浏览 42
已采纳

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

I am trying to embed a drop down list to an update page, it works fine but I am having problems with option selected part. When an option is shown it also duplicates it in the list. Is there any way I can say if record is used do not use it again with 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条回答 默认 最新

  • douyue2313 2013-04-28 00:53
    关注

    It seems like simple if condition will solve the case for you:

    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>";
        }
    }
    

    Additionally you should always sanitize $_GET / $_POST params, in your example:

    $player_id = intval($_GET['id']);
    

    Intval will return 0 if the given format is not numeric, so your sql query is safe from this moment.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大