tags:

views:

39

answers:

2

I have a list of users in my table. How would I go about taking that list and returning it as one PHP variable with each user name separated by a comma?

+7  A: 

You could generate a comma-separated list with a query:

SELECT GROUP_CONCAT(username) FROM MyTable

Or else you could fetch rows and join them in PHP:

$sql = "SELECT username FROM MyTable";
$stmt = $pdo->query($sql);
$users = array();
while ($username = $stmt->fetchColumn()) {
    $users[] = $username;
}
$userlist = join(",", $users);
Bill Karwin
Of course, the usual warning: `GROUP_CONCAT()` is length-limited, usually to 1024 characters. Any additional data after that is silently dropped.
Marc B
@Marc B: Yep, that's a good caveat.
Bill Karwin
A: 

You would fetch the list from the database, store it in an array, then implode it.

Andrew Dunn