user3140296
user3140296

Reputation: 169

Remove last Comma from while loop

My code is resulting in a output like this

Title1,1,Title2,2,

How can i remove the last comma from this?

$comma = ",";

$query = "SELECT name, listid FROM playlist ORDER BY id DESC";
$result = $mysqli->query($query);

while(list($name, $listid) = $result->fetch_row()) {
    echo $name;
    echo $comma;
    echo $listid;
echo $comma;
}

Upvotes: 3

Views: 4841

Answers (7)

Sohil Shingala
Sohil Shingala

Reputation: 204

try this

 $comma = ",";
    $html = ""; 

    $query = "SELECT name, listid FROM playlist ORDER BY id DESC";
    $result = $mysqli->query($query);

    while(list($name, $listid) = $result->fetch_row()) {
        $html .= $name.$comma.$listid.$comma;   
    }

   echo substr($html, 0, strlen($html) - 2);

Upvotes: 1

user3034685
user3034685

Reputation: 1

$result = mysqli_query($con,$query);
$num_rows= mysqli_num_rows($result);
$ctr=0;
while($row=mysqli_fetch_array($result)){
$ctr++;
    echo $row['example'];
    if($ctr!=$num_rows){
        echo ',';}
    else{
        echo '';
    }
}

Upvotes: 0

Subin
Subin

Reputation: 3563

I would recommend going with Joseph Silber's answer, although this would work :

$comma = ",";
$k=0;
$query = "SELECT name, listid FROM playlist ORDER BY id DESC";
$result = $mysqli->query($query);
while(list($name, $listid) = $result->fetch_row()) {
    if($k!=0){
     echo $comma;
    }
    echo $name;
    echo $comma;
    echo $listid;        
    $k++;
}

Upvotes: 0

E. S.
E. S.

Reputation: 2919

You can try this:

$query = "SELECT name, listid FROM playlist ORDER BY id DESC";
$result = $mysqli->query($query);

$data = array();
while(list($name, $listid) = $result->fetch_row()) {
    $data[] = $name.",".$listid;
}

echo implode(',', $data);

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 219936

$lines = array();

while(list($name, $listid) = $result->fetch_row()) {
    $lines[] = "$name,$listid";
}

echo implode(',', $lines);

Upvotes: 10

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

Use trim

<?php
$str = "1,2,3,4,5,";
echo trim($str, ",");

Output

1,2,3,4,5

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227270

Don't manually echo commas. Just make an array, then implode it.

echo implode(',', array($name, $listid));

Upvotes: 8

Related Questions