Reputation: 9314
I want to populate course list inside a dropdown but use the id from the student table to select its value in the edit page.
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 */
+----+--------+-----+--------+
I am populating the course table database inside a dropdown like this in the create new student page.
$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] │
└────┴────────┴─────┴─────────┴────────┘
I am stuck here
$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>";
the code above generates the course inside the dropdown list, but the value is not selected. I want to combine two tables into one inside the dropdown.
Please help me!
Upvotes: 0
Views: 1145
Reputation: 2633
This is assuming you have an object $student
which is the row from students
corresponding to the current user.
$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>';
Upvotes: 1
Reputation: 2738
Try This
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>";
Upvotes: 0