1

我想用逗号分隔来自数据库的值。我找不到执行此操作的 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;
}
4

3 回答 3

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

于 2012-12-18T20:36:44.593 回答
1

试试这个:

$sub = '';    
while($stmt->fetch(PDO::FETCH_BOUND)){
    if($sub == '')
        $sub = $name;
    else
        $sub .= ',' . $name;
}
于 2012-12-18T20:36:16.797 回答
1

使用分隔符变量

$delim = "";
while($stmt->fetch(PDO::FETCH_BOUND)){
    $sub .= $delim;
    $sub .= $name;
    $delim = ", ";
}
于 2012-12-18T20:37:24.467 回答