我想用逗号分隔DB出来的值。我找不到一种SQL方法,如果我尝试在while循环中执行它,它会在字符串的末尾添加一个逗号,这是我不想要的。
private function retrieve_subjects(){
$dbh = $this->connect();
$stmt = $dbh->prepare("SELECT name FROM subject");
$stmt->execute();
$stmt->bindColumn('name', $name);
while($stmt->fetch(PDO::FETCH_BOUND)){
$sub .= $name;
}
return $sub;
}
答案 0 :(得分:2)
尝试使用implode
。
PHP:http://php.net/manual/en/function.implode.php
MySQL(GROUP_CONCAT):http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat
答案 1 :(得分:1)
尝试一下:
$sub = '';
while($stmt->fetch(PDO::FETCH_BOUND)){
if($sub == '')
$sub = $name;
else
$sub .= ',' . $name;
}
答案 2 :(得分:1)
使用分隔符变量
$delim = "";
while($stmt->fetch(PDO::FETCH_BOUND)){
$sub .= $delim;
$sub .= $name;
$delim = ", ";
}