0

I need one help.I need to join DB value as string with comma(,) separator using PHP and Mysql.I am explaining my table below.

db_order:

id         name

1           Rahul

2           Raj


3           Shiv

4          Hari


$qry=mysqli_query($con,"select * from db_order");
while($row=mysqli_fetch_array($qry)){
   $data[]=$row;
}
print_r($data);

From my table i need to join all name with comma(,) so that result should like this Rahul,Raj,Shiv,Hari by executing the query.Please help me.

4
  • 1
    Do you already have tried to solve it yourself? You got to have at least some code, right? Commented Mar 31, 2016 at 9:48
  • i can only fetch the name using query but little bit confused how to join finaly with comma. Commented Mar 31, 2016 at 9:50
  • 1
    Then you should at least show your code till the point when you fetch the results of the query Commented Mar 31, 2016 at 9:51
  • Search: explode() function in PHP Commented Mar 31, 2016 at 9:55

4 Answers 4

1

Use GROUP_CONCAT :

SELECT group_concat(name separator ',') FROM YourTable
Sign up to request clarification or add additional context in comments.

Comments

0

If you have to use php then it will be like

$qry = mysqli_query($con,"select * from db_order");
$str = '';
while($row = mysqli_fetch_array($qry)){
   $str .= $row['name'].",";
}
$data = rtrim($str, ",");
echo $data;

Comments

0

You can directly get values from ur query by comma separated.

If you are using mysql, then you can get name of table comma separated like

select GROUP_CONCAT(name) from <table_name>;

and if you have database in oracle then u can use wm_concat() in place of GROUP_CONCAT().

Comments

0

Please try this:

<?php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'test';

$con = mysql_connect($server, $username, $password) or die("Error:" . mysql_error());
mysql_select_db($database, $con) or die("Unable to select DB" . mysql_error());

$qry = "SELECT id, name FROM users";

$res = mysql_query($qry, $con) or die("Error to execute query " . mysql_error());

$users = '';
if (mysql_num_rows($res)) {
    while ($row = mysql_fetch_array($res)){
        if ($users) {
            $users .= ',' . $row['name'];
        } else {
            $users = $row['name'];
        }
    }
}

echo $users;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.