What are the best practices for using SELECT elements in PHP forms to display values from related tables?

When displaying values from related tables in a PHP form using SELECT elements, it is best practice to query the related table for the values and populate the SELECT element with the retrieved data. This ensures that the values displayed in the form are up-to-date and accurate. Additionally, using prepared statements can help prevent SQL injection attacks.

// Assuming we have a database connection established

// Query to retrieve values from a related table
$stmt = $pdo->prepare("SELECT id, name FROM related_table");
$stmt->execute();
$relatedValues = $stmt->fetchAll();

// Populate SELECT element with retrieved values
echo '<select name="related_value">';
foreach ($relatedValues as $value) {
    echo '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
}
echo '</select>';