我的表中有一个用户列表。我如何获取该列表并将其作为一个PHP变量返回,每个用户名用逗号分隔?
答案 0 :(得分:7)
您可以使用查询生成以逗号分隔的列表:
SELECT GROUP_CONCAT(username) FROM MyTable
否则你可以获取行并在PHP中加入它们:
$sql = "SELECT username FROM MyTable";
$stmt = $pdo->query($sql);
$users = array();
while ($username = $stmt->fetchColumn()) {
$users[] = $username;
}
$userlist = join(",", $users);
答案 1 :(得分:1)
你会fetch the list from the database,将其存储在an array,然后implode
。
答案 2 :(得分:0)
我能弄清楚的最好方法是存储每个列或字段的结果,然后回显内爆:
$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
这花了我一段时间来弄清楚该怎么做。希望对您有帮助!