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
- What are the best practices for escaping user input in PHP to prevent SQL injection vulnerabilities when querying a database?
- What are the different line endings used for Windows, Linux, and Mac systems in PHP?
- What are the benefits of breaking out of PHP code to insert HTML elements directly in WordPress development?