将所有 while 结果分配给变量 [英] assign all while results to a variable

查看:59
本文介绍了将所有 while 结果分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选择语句.它从数据库中选择我所有的标签.每个标签都是一个条目,因此当查询获得结果时,如果在 while 语句中回显,它们将作为 tag1tag2tag3 出现.当我在 while 语句之外回显结果时,我得到 tag3.结果我想得到 tag1,tag2,tag3.解决这个问题的最佳方法是什么?

I have a select statement. It selects all my tags from a database. Each tag is an entry so when the query gets results they come out as tag1tag2tag3 if echoed within the while statement. When I echo the results outside the while statement I get tag3. I would like to get tag1,tag2,tag3 as a result. What is the best way to approach this?

$sql = "SELECT name FROM tags WHERE vid_id=?";
$gettags = $conn->prepare($sql);
$result=$gettags->execute(array($vid_id));
while ($row=$gettags->fetch(PDO::FETCH_ASSOC)){
$tags=$row['name'];
}
echo $tags; //produces tag3 if entries are tag1tag2tag3

推荐答案

您每次迭代都在重新分配 $tags.所以它只输出返回的最后一个标签.

You are reassigning $tags each iteration. So it only outputs the last tag returned.

在这种情况下,通常先构建一个数组,然后使用implode() 用于输出.

It's common to build an array in this case and then use a function like implode() for the output.

$tags = array()
while ($row=$gettags->fetch(PDO::FETCH_ASSOC)){
  $tags[] = $row['name'];
}
echo implode(', ', $tags);

注意:根据上下文和您的数据库平台,您可以完全在数据库级别使用类似GROUP_CONCAT()

Note: Depending on the context and your DB platform, you may be able to do this entirely at the database level with something like GROUP_CONCAT()

这篇关于将所有 while 结果分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆