PHP + SQL: Results seperated by comma

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bla5e
Forum Contributor
Posts: 234
Joined: Tue May 25, 2004 4:28 pm

PHP + SQL: Results seperated by comma

Post by bla5e »

Noob question, but how do I stop a comma from appearing after the last result?

Code: Select all

echo '<i>Likes: </i>';
    while ($rows = pg_fetch_assoc($like)){
      echo $rows['author'];
      echo ', ';
    }
    echo '<br><i>Dislikes: </i>';
    while ($row = pg_fetch_assoc($dislike)) {
      echo $row['author'];
      echo ', ';
    }
thanks in advance.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: PHP + SQL: Results seperated by comma

Post by John Cartwright »

I tend to store my results in an array, which makes it simple to create comma seperated output, i.e.,

Code: Select all

$likes = array();
while ($rows = pg_fetch_assoc($like)){
   $likes[] = $rows['author'];
}

echo 'Likes: '. implode(', ', $likes); 
bla5e
Forum Contributor
Posts: 234
Joined: Tue May 25, 2004 4:28 pm

Re: PHP + SQL: Results seperated by comma

Post by bla5e »

ty awesome idea!
Post Reply