Stick MYSQL query results into string separated by a comma
The first query i am making is for all of the Id's associated with a user:
$DBH = getDBH();
$stmt = $DBH->prepare("SELECT id FROM list WHERE user = ?");
$stmt->bind_param("s",$userid);
$stmt->execute();
$stmt->bind_result($ids);
$stmt->fetch();
$stmt->close();
currently stored in 开发者_高级运维the table is as follow:
ID user
1 example
4 example
7 example
15 example
The id's are not known before the query and the amount of id's associated with the user will be continuously growing and shrinking.
So my question is how can i query for these id's and stick them into a string with each id separated by a comma
ex: 1,4,7,15, etc, etc.
EDIT: USING GROUP CONCAT()
$stmt = $DBH->prepare("SELECT GROUP_CONCAT(id) as id FROM list WHERE user = ? GROUP BY id");
$stmt->bind_param("s",$userid);
$stmt->execute();
$stmt->bind_result($id);
Take a look at group_concat() function
Plese note that the max length that the string can take is specified by group_concat_max_len() variable and by default is 1024 chars.
You can see yours with this query
show variables like 'group%'
精彩评论