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
2010-09-28 00:22:27
Of course, the usual warning: `GROUP_CONCAT()` is length-limited, usually to 1024 characters. Any additional data after that is silently dropped.
Marc B
2010-09-28 00:27:01
@Marc B: Yep, that's a good caveat.
Bill Karwin
2010-09-28 00:42:16
A:
You would fetch the list from the database, store it in an array, then implode
it.
Andrew Dunn
2010-09-28 00:23:42