将 MYSQL 查询结果粘贴到以逗号分隔的字符串中
我要做的第一个查询是针对与用户关联的所有 ID:
$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();
当前存储在表中的内容如下:
ID user
1 example
4 example
7 example
15 example
在查询之前,ID 是未知的,与用户关联的 ID 数量将不断增长和缩小。
所以我的问题是如何查询这些 id 并将它们粘贴到一个字符串中,每个 id 用逗号分隔
: 1,4,7,15 等等
编辑:使用 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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看一下 group_concat() 函数,
请注意,字符串可以采用的最大长度由 group_concat_max_len() 变量指定,默认情况下为 1024 个字符。
您可以通过此查询查看您的
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