我想用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;
}
?>
一旦我从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>";
}
?>
这是另一种方法: