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,564
  • 3
  • 18
  • 41

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
  • 23,254
  • 3
  • 51
  • 94
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,443
  • 7
  • 33
  • 51
0

Using rtrim().Like below

rtrim($groupRow['group_name'])
Mahadeva Prasad
  • 709
  • 8
  • 19