How can the GROUP_CONCAT function be effectively utilized in PHP to display concatenated results from a MySQL query?
The GROUP_CONCAT function in MySQL can be effectively utilized in PHP to display concatenated results from a query by fetching the data from the database using a SELECT statement and then using the GROUP_CONCAT function in the query to concatenate the results. Finally, the concatenated results can be displayed in PHP using the fetched data.
<?php
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Fetch concatenated results from the database using GROUP_CONCAT
$query = "SELECT GROUP_CONCAT(column_name SEPARATOR ', ') AS concatenated_results FROM table_name";
$result = mysqli_query($connection, $query);
// Display concatenated results
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['concatenated_results'];
}
} else {
echo "No results found";
}
// Close connection
mysqli_close($connection);
?>