Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implode an array into a comma separated string from mysql query

For the last 1 1/2 days I've been trying to store 16 row id's into a string and separate each id with a comma. The array I am getting is from MySQL. The error I am getting is

implode() function:passed invalid arguments

$str=array();
$string="";
while($row = mysql_fetch_row($result)) 
{
    $user_id=$row;
    $str=$user_id;
    foreach($str as $p=>$v){
        comma($v);
    }
}

function comma($v){
    $string= implode(",",$v); echo $string;
}
like image 709
anjelott1 Avatar asked Jul 22 '12 11:07

anjelott1


People also ask

How can I convert an array to comma separated string?

To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.

How pass comma separated values in MySQL query?

In MySQL, you can return your query results as a comma separated list by using the GROUP_CONCAT() function. The GROUP_CONCAT() function was built specifically for the purpose of concatenating a query's result set into a list separated by either a comma, or a delimiter of your choice.

How do you separate array values with commas?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How do you get a comma separated string from an array in C?

How to get a comma separated string from an array in C#? We can get a comma-separated string from an array using String. Join() method. In the same way, we can get a comma-separated string from the integer array.


1 Answers

Try something like this:

$ids = array(); 
while ($row = mysql_fetch_assoc($result))  
{
    $ids[] = $row["UserID"]; 
} 
echo implode(", ", $ids);

Replace "UserID" with the columnname of the id in your table.

So: first you build the array, next you implode the array into a string.

like image 125
huysentruitw Avatar answered Oct 17 '22 04:10

huysentruitw