将 MySQL 结果转换为逗号分隔值 [英] Converting MySQL results into comma separated values

查看:74
本文介绍了将 MySQL 结果转换为逗号分隔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 mysql 语句会产生一堆结果.除了最后一个结果,我想用逗号分割每个结果.我在想我需要一个 for 循环,但我不太确定如何去做.我应该将结果作为数组获取并循环遍历它们吗?我在想我应该计算行数,然后当 for 到达最后一个结果时,它不使用逗号.

I have a mysql statement that will produce a bunch of results. I want to split each result with a comma except the last result. I was thinking that I would need a for loop but I am not quite sure how to go about it. Should I get my results as an array and loop through them? I was thinking that I should count the rows and then when the for reaches the last result it doesn't use a comma.

我已经习惯于使用 while 来获取结果,以至于我有点菜鸟.我将不胜感激.

I am so used to just getting the results with while that I am a bit of a noob using for. I would appreciate any advice.

显然行不通,因为最后的结果会有一个逗号.

$sql = 'SELECT * FROM tags WHERE vid_id=?';
$stmt_tags = $conn->prepare($sql);
$result=$stmt_tags->execute(array($vid_id));
$tag_count=$stmt_tags->rowCount();
while ($row = $stmt_tags->fetch(PDO::FETCH_ASSOC)) {

    $tags=htmlspecialchars( $row['name'], ENT_NOQUOTES, 'UTF-8' );
    $tags=$tags.',';
    echo $tags;

}

提前致谢.

推荐答案

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

这篇关于将 MySQL 结果转换为逗号分隔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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