How can the DISTINCT keyword in a MySQL SELECT query be used to prevent duplicate entries in a dropdown list populated from a database in PHP?
When populating a dropdown list from a database in PHP, the DISTINCT keyword in a MySQL SELECT query can be used to prevent duplicate entries from being displayed in the dropdown list. By using DISTINCT, only unique values will be retrieved from the database and displayed in the dropdown list. This ensures that each option in the dropdown list is distinct and eliminates any duplicate entries.
<?php
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query to select distinct values for the dropdown list
$query = "SELECT DISTINCT column_name FROM table_name";
// Execute the query
$result = mysqli_query($connection, $query);
// Populate the dropdown list with distinct values
echo "<select>";
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['column_name'] . "'>" . $row['column_name'] . "</option>";
}
echo "</select>";
// Close the database connection
mysqli_close($connection);
?>
Keywords
Related Questions
- What potential pitfalls should be avoided when inserting text into a database using PHP?
- How can PHP scripts effectively handle and process data received from web requests, such as converting and storing the data in a specific format like CSV?
- What are the potential pitfalls of using different character encodings in PHP when writing to text files?