implode doesn't work

Discussion in 'PHP' started by bobby9101, Feb 21, 2007.

  1. #1
    I have 50 members in a a database, and I want to comma delimit them... so I use:
    $fetch = mysql_query("SELECT email FROM members");
    $data = mysql_fetch_array($fetch);
    $delimited = implode(", ", $data);
    Code (markup):
    However it just shows the first entry twoce like: email1, email1
    so if I use
    $fetch = mysql_query("SELECT email FROM members");
    $data = mysql_fetch_array($fetch, MYSQL_ASSOC);
    $delimited = implode(", ", $data);
    Code (markup):
    then it just displays email1

    How can I get it to comma delimit all emails?
     
    bobby9101, Feb 21, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    You have to loop over the results.

    
    
    $emails = array();
    
    $fetch = mysql_query("SELECT email FROM members");
    
    while ($data = mysql_fetch_array($fetch))
    {
         array_push($data['email'], $emails);
    }
    
    $delimited = implode(", ", $emails);
    
    PHP:
     
    nico_swd, Feb 21, 2007 IP
  3. picouli

    picouli Peon

    Messages:
    760
    Likes Received:
    89
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You need to run through the result set:
    $fetch = mysql_query("SELECT email FROM members");
    while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
      $emails[] = $row['email'];
    }
    $delimited = implode(", ", $emails);
    PHP:
    HTH, cheers! :)
     
    picouli, Feb 21, 2007 IP
    bobby9101 likes this.
  4. bobby9101

    bobby9101 Peon

    Messages:
    3,292
    Likes Received:
    134
    Best Answers:
    0
    Trophy Points:
    0
    #4
    ahh ok thanks, I swear i'll catch onto this sooner or later
     
    bobby9101, Feb 21, 2007 IP
  5. -NB-

    -NB- Peon

    Messages:
    153
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Yeah, right there you're only telling it to grab the first result ;). The code above is the stuff you want to use. Also, to remove the trailing comma, add this:
    $delimited = substr($delimited, 0, strlen($delimited) - 2);
    PHP:
    All set :)
     
    -NB-, Feb 21, 2007 IP
  6. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #6
    There won't be a trailing comma at the end, cause we're using implode().
     
    nico_swd, Feb 22, 2007 IP