Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add comma between DB rows when creating a string using concatenation

i am creating a large string from all rows inside a database.

This works fine, however i am having issues when using the string as an array as the ending of each database row does not end with a comma so i am getting a joining between the last and first word.

How can i change this:

  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // concatenate all the tags into one string
    $tags .= $row['tags'];
  }

So that each of the $row['tags'] has a comma after it?

Hope this makes sense.

like image 513
Lovelock Avatar asked Aug 22 '26 17:08

Lovelock


2 Answers

I would go with:

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
   // concatenate all the tags into one string
   $tags[] = $row['tags'];
}
$tagsString = implode(",", $tags);
like image 110
skywalker Avatar answered Aug 25 '26 06:08

skywalker


You can concatenate your tags and comma at each iteration

$tags .= $row['tags'] . ',';

To remove the last comma you just need substr()

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // concatenate all the tags into one string
    $tags .= $row['tags'].',';
}

$tags = substr($tags,0,-1);
like image 43
Fabio Avatar answered Aug 25 '26 06:08

Fabio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!