echo selected in html select option if value exists in array

echo selected in html select option if value exists in array

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

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

这是我目前拥有的基本代码(减去所有无效的代码)。希望有人能帮帮他。

 $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 之前完成它。

你可以试试

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

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

改变

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

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

虽然公平地说,@rept1d 的回答应该也能正常工作。