11

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;
}
Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51
anjel
  • 1,355
  • 4
  • 23
  • 35
  • 3
    Please, stop being a bad guy and do not store comma-separated values into a unique field. Use another table and store each value into its own row. (You are creating problems that wouldn't exist if your shema was well structured.) – OcuS Jul 22 '12 at 11:36
  • implode takes an array as a second parameter – Leon Jul 22 '12 at 11:39
  • @oCuS I don't know if he's trying to "store comma-separated values into a unique field", he just says he want to store it into a string. – Leon Jul 22 '12 at 11:43
  • @Leon: "I've been trying to store 16 row id's into a string and separate each id with a comma". It says enough to me. That's a bad design. Period. – OcuS Jul 22 '12 at 11:45
  • 2
    Also, you shouldn't be using the `mysql_*` functions, since they're a) insecure, and b) being deprecated (see the [red box](http://php.net/manual/en/function.mysql-connect.php)). You should be using prepared statements with [PDO](http://www.php.net/manual/en/ref.pdo-mysql.php) or [MySQLi](http://www.php.net/manual/en/book.mysqli.php) instead. – Ricardo Altamirano Jul 22 '12 at 11:53

3 Answers3

17

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.

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
3

There is my solution:

SELECT GROUP_CONCAT(UserID) as string  FROM Users;

For this function the delimiter is ',' by default.

perfectio
  • 69
  • 3
0
$query = 'SELECT id FROM your_table';
$rs = mysql_query($query);

$row = mysql_fetch_array($result);
return implode(',', $row);

the result 1,2,3...

Darwin
  • 62
  • 2
  • 8