What are the best practices for structuring PHP code to efficiently handle database queries for populating select elements?
When populating select elements in a web application using PHP, it is important to efficiently handle database queries to avoid performance issues. One best practice is to separate the database query logic from the presentation layer by creating a function that retrieves the data from the database and returns it in a format that can be easily used to populate the select element. This helps improve code organization and maintainability.
// Function to retrieve data from the database for populating a select element
function getSelectOptions($tableName, $valueField, $textField) {
$options = array();
// Perform database query to retrieve data
$query = "SELECT $valueField, $textField FROM $tableName";
$result = mysqli_query($connection, $query);
// Loop through the results and store them in an array
while ($row = mysqli_fetch_assoc($result)) {
$options[$row[$valueField]] = $row[$textField];
}
return $options;
}
// Usage example
$options = getSelectOptions('products', 'product_id', 'product_name');
foreach ($options as $value => $text) {
echo "<option value='$value'>$text</option>";
}