What is the purpose of using the DISTINCT keyword in a MySQL query when retrieving data from a table?
When retrieving data from a table in MySQL, the DISTINCT keyword is used to ensure that only unique values are returned for a specific column or combination of columns. This can be useful when you want to eliminate duplicate rows from the result set and only display distinct values.
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query to select distinct values from a table
$query = "SELECT DISTINCT column_name FROM table_name";
// Execute the query
$result = mysqli_query($connection, $query);
// Fetch and display the results
while ($row = mysqli_fetch_assoc($result)) {
echo $row['column_name'] . "<br>";
}
// Close the connection
mysqli_close($connection);
Related Questions
- What potential pitfalls should PHP beginners be aware of when trying to execute HTML code within PHP functions or conditional statements?
- What best practices should be followed when creating links within PHP scripts to ensure proper functionality?
- What is the common mistake made when using the unlink function in PHP?