What are the advantages of using DISTINCT in PHP MySQL queries?
When retrieving data from a MySQL database using PHP, you may encounter duplicate rows in the result set. This can be problematic if you only want to display unique values. To solve this issue, you can use the DISTINCT keyword in your MySQL query to eliminate duplicate rows and only return unique values.
<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
// Query to retrieve unique values from a table
$sql = "SELECT DISTINCT column_name FROM table_name";
if($result = $mysqli->query($sql)){
if($result->num_rows > 0){
while($row = $result->fetch_array()){
echo $row['column_name'] . "<br>";
}
// Free result set
$result->free();
} else{
echo "No records found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
// Close connection
$mysqli->close();
?>