How can PHP be used to prevent duplicate values from being displayed in a dropdown menu?

When populating a dropdown menu with values from a database using PHP, it is important to prevent duplicate values from being displayed to provide a better user experience. One way to achieve this is by fetching the unique values from the database using a SELECT DISTINCT query, which ensures that only unique values are retrieved and displayed in the dropdown menu.

// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch unique values from the database
$sql = "SELECT DISTINCT column_name FROM table_name";
$result = $conn->query($sql);

// Populate dropdown menu with unique values
echo '<select>';
while($row = $result->fetch_assoc()) {
    echo '<option value="' . $row['column_name'] . '">' . $row['column_name'] . '</option>';
}
echo '</select>';

// Close database connection
$conn->close();