Simple While Loop Question

Discussion in 'PHP' started by timallard, May 7, 2009.

  1. #1
    Hello,

    Im running a loop pulling in data from a SQL query seen below:

    <?php while ($row7 = mysql_fetch_array($result7)){ echo $row7['COUNT(Category)'] . ','; } ?>

    I need to have my data to print out, comma delimited.

    0,23,42,53,5,2,4 etc BUT with this syntax, im getting one last comma at the end 5,3,6,3,6, that is messing up my data. how can I ommit the last comma from the loop?

    Thank you!!!!
     
    timallard, May 7, 2009 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    You basically need to get the number of rows in the query.

    
    $rows = mysql_num_rows($result7);
    
    $count = 1;
    
    while ($row7 = mysql_fetch_array($result7)){
    
    echo $row7['COUNT(Category)'] . ($count < $rows) ? ',' : '' ;
    
    $count++;
    }
    
    PHP:
    You can break this out of shorthand if needed as well.
     
    jestep, May 7, 2009 IP
  3. pixmania

    pixmania Peon

    Messages:
    229
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3

    How about using implode. Then just echo as your doing but remove your comma, see below, not tested.

    
    $row7 = implode(",", $result7);
    echo $row7['COUNT(Category)'];
    
    
    Code (markup):
     
    pixmania, May 7, 2009 IP
  4. Progg

    Progg Peon

    Messages:
    38
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Many solutions to this.You could even preg_replace("/\,$/is","",$mysqlResult); meaning that if it sees the last character as a , it will replace it with an empty string
     
    Progg, May 7, 2009 IP
  5. donfhaden

    donfhaden Peon

    Messages:
    50
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    I prefer simpler solution
    
    <?php
    $data = "";
    while ($row7 = mysql_fetch_array($result7))
    {
      $data = "," . $row7['COUNT(Category)']; 
    }
    $data = substr($data, 1);
    
    PHP:
     
    donfhaden, May 8, 2009 IP