【问题标题】:echo selected in html select option if value exists in array如果数组中存在值,则在 html 选择选项中选择回显
【发布时间】:2021-10-20 15:47:59
【问题描述】:

我已经搜索了几天并尝试了所有方法,但我似乎无法正常工作。

问题: 我有一个用户个人资料,用户可以在其中从下拉菜单中选择一些爱好。该用户还可以编辑他的个人资料。在此编辑页面上,我想显示一个下拉列表,其中选择了先前选择的爱好,并显示其余可用的爱好选项以供选择。

这是我到目前为止的基本代码(减去所有不起作用的代码)。我希望有人可以帮助他。

 $existing_hobby_values = array("Football", "Tennis", "Volleyball");
 $sql = "select hobby from hobbies ORDER BY id ASC";
 $result = mysqli_query($con, $sql);
    if (mysqli_num_rows($result) > 0) {
        echo "<select multiple>";
            while($row = mysqli_fetch_assoc($result)) {
            $interesse = $row['hobby'];
                                                    
            //if{$interesse = in_array($existing_hobby_values) echo "selected" inside option }                                  
                                                    
            echo "<option value='$interesse'>$interesse</option>";

            }
            echo "</select>";
            }

顺便说一句...我知道我应该开始使用 PDO 而不是 Mysqli,但是因为这个项目有一个截止日期,所以我必须在开始学习 PDO 之前完成它。

【问题讨论】:

    标签: php html mysql arrays select


    【解决方案1】:

    你可以试试

    while ($row = mysqli_fetch_assoc($result)) {
        $interesse = $row['hobby'];
        echo '<option ';
        if (in_array($interesse, $existing_hobby_values)) {
            echo 'selected ';
        }
        echo "value='$interesse'>$interesse</option>";
    }
    

    而且你绝对应该对你的制表做点什么。

    【讨论】:

      【解决方案2】:

      改变

      echo "<option value='$interesse'>$interesse</option>";
      

      echo "<option value='$interesse' ".( in_array($intresse,$existing_hobby_values) ? "SELECTED ": "" ) .">$interesse</option>";
      

      公平地说,@rept1d 的回答也应该可以正常工作。

      【讨论】:

        猜你喜欢
        • 2018-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-18
        • 1970-01-01
        • 2014-02-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多