How can you prevent duplicate entries in a dropdown menu populated from a MySQL database in PHP?
To prevent duplicate entries in a dropdown menu populated from a MySQL database in PHP, you can use the DISTINCT keyword in your SQL query to retrieve only unique values from the database table. This will ensure that each option in the dropdown menu is unique and there are no duplicates.
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve unique values from the database table
$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();
?>