Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

I would go with:

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

You can do :

$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$atags = array_column($row, 'tags');
$tags = implode(',',$atags);

It's PDO, Luke

$sql = "SELECT tags FROM table WHERE something = ?";
$stm = $pdo->prepare($sql);
$stm->execute([$condition]);
$tags = implode(",",$stm->fetchAll(PDO::FETCH_COLUMN, 0));

It's Mysql, Luke

$sql = "SELECT group_concat(tags) FROM table WHERE something = ?";
$stm = $pdo->prepare($sql);
$stm->execute([$condition]);
$tags = $stm->fetcnColumn();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top