PHP:如何在下拉列表中列出文件夹中的文件,然后根据mysql条目选择其中一个


PHP: How to list files of a folder in a dropdown and then select one of them according to mysql entry

我正在尝试创建一个下拉列表,列出特定文件夹的内容。为此,我使用的代码运行良好:

<select name="level">
<?php
    $dirname = "../images/page_images/";
    $dirhandle = opendir($dirname);
    while($file = readdir($dirhandle))
    {
    if ($file != "." && $file != "..")
    {
    if (is_file($dirname.$file))
    {
    echo "<option value='" . $file .">" . $file . "</option>"; 
    }
    else
    {
    echo "mappe: " . $file . "<br>";
    }
    }
    }
     ?> 
</select>

现在,我希望下拉栏检查一个mysql条目并进行匹配,以便在数据库中写入的文件就是所选的文件。为此,我认为我的选项值应该是这样的:($pageImage是从mysql加载的值(

  <option <?php echo ($pageImage) == $file ? "selected" : "" ?> value="$file">$file</option>

我的问题是,如何将这两个脚本合并在一起?

试试这个简单的方法来列出文件夹中的文件名。

<select name="level">
    <?php
    foreach (glob("../images/page_images/*.{jpg,gif}") as $filename) {
        echo "<option value='" . $filename .">" . $filename . "</option>"; 
    }
    ?>
    </select>
echo "<option value='{$file}'" . ($pageImage == $file ? " selected" : "") . ">{$file}</option>";

echo '<option value="' . $file . '"' . ($pageImage == $file ? " selected" : "") . '>' . $file . '</option>';

Docs:PHP字符串运算符