带有php和mysql的动态选择元素未显示下拉菜单

问题描述 投票:-1回答:2

我想用php动态填充选择选项,并且我与数据库的连接正常工作,因为下面index.php的第一部分的查询确实在页面上回显了正确的结果。但是,脚本不会在表单中显示结果,只是空白。

index.php

<?php
    //This portion that is in the file is to see that the function is working and that my echo        
    //statements for options are correct
    include "getCourses.php";
    $data = getCourses();
    foreach ($data as $row) {
        echo "<option value=\"" . $row[0] . "\">" . $row[0] . "</option>";
    }

?>

<form method="post">
    <label for="courses">Courses:</label>
    <select id="course" name="course">
    //the drop-down menu shows the correct number of options but not the text for them
    <?php
        include "getCourses.php";
        $data = getCourses();
        foreach ($data as $row) {
            echo "<option value=\"" . $row[0] . "\">" . $row[0] . "</option>";
        }       
    ?>
    </select>
    <input type="submit">
</form>

如果需要,这里是getCourses.php的内容:

?php
include "utils/conn.php";

function getCourses() {
    //create query string
    $query = "SELECT DISTINCT course_id FROM office_hours";
    //query
    global $conn;
    if ($conn-> connect_errno) {
        echo "Failed to connect to MySQL: " . $conn -> connect_error;
    }
    $data = array();
    //currently gets stuck on the query() function and doesn't finish computing
    if($result = $conn->query($query)) {
        while($row = $result->fetch_array(MYSQLI_NUM)) {
            array_push($data, $row);
        }
    }
    //return list of unique courses
    return $data;
}

?>
php
2个回答
0
投票

一旦我从index.php文件中删除了代码:

<?php
    //This portion that is in the file is to see that the function is working and that my echo        
    //statements for options are correct
    include "getCourses.php";
    $data = getCourses();
    foreach ($data as $row) {
        echo "<option value=\"" . $row[0] . "\">" . $row[0] . "</option>";
    }
?>

0
投票

这是另一种方法:

© www.soinside.com 2019 - 2024. All rights reserved.