What is the purpose of using the DISTINCT keyword in a MySQL query?
When querying a database, sometimes there may be duplicate rows returned that you want to eliminate. In such cases, you can use the DISTINCT keyword in a MySQL query to only return unique rows, removing any duplicates. This can be useful when you only want to see distinct values in a specific column or when you want to ensure that each row returned is unique.
<?php
// Connect to 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);
}
// Query with DISTINCT keyword to select unique rows
$sql = "SELECT DISTINCT column_name FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column Value: " . $row["column_name"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- How can variables be properly concatenated with file names in PHP to display images correctly?
- How can the regex pattern provided in the forum thread be modified or improved for better performance or accuracy?
- In what scenarios would using XPath be more efficient than looping through DOM elements in PHP?