1
votes

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
4

4 Answers

4
votes
$tags = array()
while ($row = ...) {
   $tags[] = $row['name'];
}
echo implode($tags);
2
votes
$sql = "SELECT name FROM tags WHERE vid_id=?";
$gettags = $conn->prepare($sql);
$result=$gettags->execute(array($vid_id));
$tags = '';
while ($row=$gettags->fetch(PDO::FETCH_ASSOC)){
   $tags .= $row['name']; //concatenate the strings
}
echo $tags; //produces tag1tag2tag3
2
votes

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

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

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()

2
votes
$tags = array();
$i = 0;


while ($row=$gettags->fetch(PDO::FETCH_ASSOC)){
    $tags[$i]=$row['name'];
    $i++;
}

echo $tags;