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.
$tags = array();
while ($row = $stmt_tags->fetch(PDO::FETCH_ASSOC)) {
$tags[] =htmlspecialchars( $row['name'], ENT_NOQUOTES, 'UTF-8' );
}
echo implode(',', $tags);
Put them all in a temporary array and use implode()
.
implode(',',$array);
$alldata = $stmt_tags->fetchAll(PDO::FETCH_ASSOC);
$tags = implode(',' array_map(function($row){
htmlspecialchars( $row['name'], ENT_NOQUOTES, 'UTF-8' );
},$alldata));
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' );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.