How can PHP be used to dynamically populate dropdown menus with course options from a database table in an enrollment form?
To dynamically populate dropdown menus with course options from a database table in an enrollment form, you can use PHP to query the database for the course options and then loop through the results to generate the dropdown menu options. This way, the dropdown menu will always display the most up-to-date list of available courses.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query database for course options
$sql = "SELECT course_id, course_name FROM courses";
$result = $conn->query($sql);
// Generate dropdown menu options
echo "<select name='course'>";
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['course_id'] . "'>" . $row['course_name'] . "</option>";
}
echo "</select>";
// Close database connection
$conn->close();
?>
Related Questions
- How can the use of explode() be a more efficient alternative to preg_match_all in certain cases in PHP?
- How can the issue of variables not being correctly retrieved from $_GET in PHP be resolved when using a form with only a submit button?
- What are the potential pitfalls of using the mail() function in PHP for sending newsletters?