What are some best practices for handling duplicate values in a MySQL query result set in PHP?
When handling duplicate values in a MySQL query result set in PHP, one common approach is to use the DISTINCT keyword in the SQL query to eliminate duplicate rows before processing the data. Another approach is to use PHP to filter out duplicate values from the result set by storing unique values in an array or using the array_unique() function. Additionally, you can also use GROUP BY clause in your SQL query to group duplicate values together and perform aggregate functions if needed.
// Assuming $conn is the MySQL database connection object and $query is the SQL query
$result = mysqli_query($conn, $query);
// Option 1: Use DISTINCT in SQL query
// $query = "SELECT DISTINCT column_name FROM table_name";
// Option 2: Use PHP to filter out duplicates
$uniqueValues = [];
while ($row = mysqli_fetch_assoc($result)) {
if (!in_array($row['column_name'], $uniqueValues)) {
$uniqueValues[] = $row['column_name'];
// Process the unique value here
}
}
// Option 3: Use GROUP BY in SQL query
// $query = "SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name";