How can PHP be used to populate a select field with data from a MySQL table?
To populate a select field with data from a MySQL table using PHP, you can query the database to retrieve the data and then loop through the results to create the options for the select field. You can then echo out the options within the select field in your HTML code.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Query to retrieve data from MySQL table
$query = "SELECT id, name FROM table_name";
$result = mysqli_query($connection, $query);
// Create select field with options
echo "<select name='select_field'>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
// Close database connection
mysqli_close($connection);
?>
Keywords
Related Questions
- Is it possible to overlay a scrollable form with a white background on top of an existing webpage using PHP and HTML in the same tab?
- Are there any common pitfalls to avoid when working with object-oriented programming and MySQL in PHP?
- How can PHP be used to create and play MIDI files in a web browser?