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?
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);
You would fetch the list from the database, store it in an array, then implode
it.
The best way I was able to figure this out was by storing the results from each col, or field, and then echoing the implode:
$result = mysqli_query($conn, $sql) //store the result
$cols = array(); //instantiate an array
while($col = mysqli_fetch_array($result)) {
$cols[] = $col['username']; //step through results and save each username in array
}
echo implode(",",$cols); //turn the array into a comma separated string and echo it
This took me a while to figure out exactly how to do this. Hope it helps!
精彩评论