1

My select query is like this, in group_name i am giving comma but I want to remove comma from last. I already tried with trim but it removes all commas, and I want to remove last comma only.

$selctGroup = "SELECT contact_id,group_name FROM contact_group
                       LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id`
                 WHERE contact_id = ".$row['contact_id'];
 $selctGroupRes = mysql_query($selctGroup);
 while($groupRow = mysql_fetch_array($selctGroupRes))
 {
   echo  $groupRow['group_name'].','; 
 }
Bruce_Wayne
  • 1,460
  • 3
  • 18
  • 39

4 Answers4

3

Instead of echoing out each line, build up a string to echo at the end. Before that, remove the lingering comma from the end with rtrim($str,",").

$str = "";
while($groupRow = mysql_fetch_array($selctGroupRes)) {
   $str .= $groupRow['group_name'].','; 
}
echo rtrim($str,",");
Drakes
  • 22,117
  • 3
  • 46
  • 91
1
$selctGroup = "SELECT contact_id,group_name FROM contact_group
                       LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id`
                 WHERE contact_id = ".$row['contact_id'];
 $selctGroupRes = mysql_query($selctGroup);
 $str='';
 while($groupRow = mysql_fetch_array($selctGroupRes))
 {
    if($str=='')
      $str=$groupRow['group_name']; 
    else
       $str.=','.$groupRow['group_name']; 
 }
 echo $str;
Apoorv Bambarde
  • 346
  • 2
  • 12
0

Store your data in array and using implode you can remove last comma

while($groupRow = mysql_fetch_array($selctGroupRes))
 {
  $result[] = $groupRow['group_name']; 
 }

echo implode(",", $result);
Saty
  • 22,213
  • 7
  • 30
  • 49
0

Using rtrim().Like below

rtrim($groupRow['group_name'])
Mahadeva Prasad
  • 689
  • 7
  • 19