Converting MySQL results into comma separated values

送分小仙女□ 提交于 2021-02-07 19:54:55

问题


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.

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.

Obviously won't work because the last result will have a comma.

$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;

}

Thanks in advance.


回答1:


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



回答2:


Put them all in a temporary array and use implode().

implode(',',$array);



回答3:


$alldata = $stmt_tags->fetchAll(PDO::FETCH_ASSOC);
$tags = implode(',' array_map(function($row){
    htmlspecialchars( $row['name'], ENT_NOQUOTES, 'UTF-8' );
},$alldata));



回答4:


And without implode() —for completeness— just add the comma before; it's easier to tell out the first row than the last one:

<?php

$tags = '';
$first = TRUE;
while ($row = $stmt_tags->fetch(PDO::FETCH_ASSOC)) {
    if($first){
        $first = FALSE;
    }else{
        $tags .= ', ';

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


来源:https://stackoverflow.com/questions/7030913/converting-mysql-results-into-comma-separated-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!