我想在下拉列表中填写课程列表,但是使用student表中的id在编辑页面中选择其值。
course
+----+-------------+
| id | course_name |
+----+-------------+
| 1 | English |
| 2 | Math |
| 3 | Social |
| 4 | Arts |
| 5 | History |
+----+-------------+
student
+----+--------+-----+--------+
| id | name | age | course |
+----+--------+-----+--------+
| 1 | John | 25 | 1 | /* English */
| 2 | Robert | 24 | 3 | /* Social */
| 3 | Nancy | 21 | 4 | /* Arts */
+----+--------+-----+--------+
我在创建新学生页面中的下拉列表中填充课程表数据库。
$dropdown_query = "SELECT * FROM course";
// other codes
echo "<select name='course' value='' required/>";
echo "<option value=''> Select the Course </option>";
foreach (mysqli_query($con, $dropdown_query) as $row){
echo "<option value='".$row['id']. "'> $row[course_name] </option>";
}
echo "</select>";
// other codes
┌────┬────────┬─────┬─────────┬────────┐
│ id │ name │ age │ course │ Edit │
├────┼────────┼─────┼─────────┼────────┤
│ 1 │ John │ 25 │ English │ [Edit] │
│ 2 │ Robert │ 24 │ Social │ [Edit] │
│ 3 │ Nancy │ 21 │ Arts │ [Edit] │
└────┴────────┴─────┴─────────┴────────┘
我被困在这里
$id = '';
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
$dropdown_query = "SELECT * FROM course";
$result = mysqli_query($con, $dropdown_query);
echo "<select name=course value=''> Course </option>";
while ($row = mysqli_fetch_array($result)) {
if($row['id'] == $id){
echo "<option value='".$row['id']. "' selected> $row[course_name] </option>";
} // if
else{
echo "<option value='" .$row['id']. "' >$row[course_name]</option>";
} // else
} // while
echo "</select>";
上面的代码在下拉列表中生成了课程,但未选中该值。我想在下拉列表中将两个表合并为一个。
请帮助我!
答案 0 :(得分:1)
假设您有一个对象$student
,它是与当前用户对应的students
行。
$dropdown_query = "SELECT * FROM course";
$courses = mysqli_query($con, $dropdown_query);
echo '<select name="course">';
while ($course = mysqli_fetch_array($courses)) {
echo "<option value='{$course['id']}'".($student['course']==$course['id'] ? ' selected="selected"' : '').">{$course['course_name']}</option>";
} // while
echo '</select>';
答案 1 :(得分:0)
试试这个
echo "<select name=course value=''> Course </option>";
//ADD EMPTY ELEMENT SO YOU CAN SEE SELECTED ELement
echo "<option value=''> Your Course </option>";
while ($row = mysqli_fetch_array($result)) {
if($row['id'] == $id){
echo "<option value='".$row['id']. "' selected> $row[course_name] </option>";
} // if
else{
echo "<option value='" .$row['id']. "' >$row[course_name]</option>";
} // else
} // while
echo "</select>";