PHP MySQL Concat Columns with Comma Example


Share:
 | Published By: Admin | Published On: Feb 07, 2022 | Category: PHP

Hello Friends,

I am going to explain you example of PHP concat columns with comma. You will learn how to concatenate two columns in PHP with comma. I would like to how to PHP concat columns with comma. This article will give you simple example of how to concatenate columns with comma in PHP query.

We will use get search concat with comma in PHP. You can understand a concept of search how to concat columns with comma in PHP server.

You can see both example of how to PHP concat with comma.

Table: users

Table: users_role

So, let's see bellow solution:

index.php
<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "db_php";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT 
            users.id, 
            users.first_name, 
            users.last_name, 
            users.email, 
            GROUP_CONCAT(users_role.role) AS role_list
        FROM `users`
        INNER JOIN users_role ON users_role.user_id = users.id
        GROUP BY users.id";

$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {
    echo '<pre>';
    print_r($row);
}

?>
Output:
Array
(
    [id] => 1
    [first_name] => Hardik
    [last_name] => Savani
    [email] => savanihd@gmail.com
    [role_list] => User,Admin
)
Array
(
    [id] => 2
    [first_name] => Aatman
    [last_name] => Infotech
    [email] => aatmaninfotech@gmail.com
    [role_list] => Manager,Admin
)
Array
(
    [id] => 3
    [first_name] => Harshad
    [last_name] => Pathak
    [email] => savanhd2@gmail.com
    [role_list] => Manager
)
It will help you...
Share: