How can you populate a select list with values from a MySQL table in PHP?
To populate a select list with values from a MySQL table in PHP, you can query the database to retrieve the values and then loop through the result set to create the options for the select list. You can then echo out the options within the select element to display them on the webpage.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query to retrieve values from MySQL table
$query = "SELECT id, name FROM table_name";
$result = mysqli_query($connection, $query);
// Create select list with values from MySQL table
echo '<select name="select_name">';
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 common pitfalls to avoid when implementing user authentication and authorization logic in PHP scripts?
- How can one ensure correct interpretation of data structures when working with SOAP services in PHP?
- How can CURL be utilized to send data to a PHP script from a remote client over the web?