How can GROUP_CONCAT be used effectively in PHP to handle multiple data outputs?

When dealing with multiple data outputs in PHP, GROUP_CONCAT can be used effectively to concatenate the values of multiple rows into a single string. This can be particularly useful when you want to display multiple values in a single column or when you want to retrieve all related values in a single query result.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Query to retrieve multiple values concatenated into a single string
$query = "SELECT user_id, GROUP_CONCAT(email) as emails FROM users GROUP BY user_id";

// Execute the query
$stmt = $pdo->query($query);

// Fetch the results
while ($row = $stmt->fetch()) {
    echo "User ID: " . $row['user_id'] . "<br>";
    echo "Emails: " . $row['emails'] . "<br><br>";
}