简体   繁体   English

从 MySQL PHP 创建逗号分隔列表

[英]Create Comma Seperated List from MySQL PHP

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?我将如何获取该列表并将其作为一个 PHP 变量返回,每个用户名用逗号分隔?

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:或者你可以获取行并在 PHP 中加入它们:

$sql = "SELECT username FROM MyTable";
$stmt = $pdo->query($sql);
$users = array();
while ($username = $stmt->fetchColumn()) {
    $users[] = $username;
}
$userlist = join(",", $users);

您将从数据库中获取列表,将其存储在一个数组中,然后对其进行内implode

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!希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM