jakeoh Posted December 17, 2007 Share Posted December 17, 2007 Noob here, obviously. I have a database of users, each with an email address. I would like to get a string with every address followed by a comma. My SQL query will go "SELECT email FROM users", but how do I format the results so that I have a nice string with all addresses separated with a comma? Link to comment https://forums.phpfreaks.com/topic/81965-getting-a-list-of-email-addresses-from-a-database/ Share on other sites More sharing options...
Northern Flame Posted December 17, 2007 Share Posted December 17, 2007 <?php // Connect to your database! $query = mysql_query("SELECT email FROM users"); while($row = mysql_fetch_array($query)){ echo $row['email'] . ", \n"; } ?> Link to comment https://forums.phpfreaks.com/topic/81965-getting-a-list-of-email-addresses-from-a-database/#findComment-416484 Share on other sites More sharing options...
corbin Posted December 17, 2007 Share Posted December 17, 2007 //assume DB conn made already $q = mysql_query('SELECT email FROM users'); $emails = array(); while($r = mysql_query($q)) { $emails[] = $r['email']; } $commaSeperated = implode(',', $emails); //or, a way to do it without array/implode (might be faster) $q = mysql_query('SELECT email FROM users'); $emails = ''; while($r = mysql_query($q)) { $emails .= $r['email'] . ','; } $emails = substr($emails, 0, strlen($emails)-2); //get rid of the trailing , Link to comment https://forums.phpfreaks.com/topic/81965-getting-a-list-of-email-addresses-from-a-database/#findComment-416485 Share on other sites More sharing options...
teng84 Posted December 17, 2007 Share Posted December 17, 2007 //assume DB conn made already $q = mysql_query('SELECT email FROM users'); $emails = array(); while($r = mysql_query($q)) { $emails[] = $r['email']; } $commaSeperated = implode(',', $emails); //or, a way to do it without array/implode (might be faster) $q = mysql_query('SELECT email FROM users'); $emails = ''; while($r = mysql_query($q)) { $emails .= $r['email'] . ','; } $emails = substr($emails, 0, strlen($emails)-2); //get rid of the trailing , you will end up having comma at the end of string think about that maybe .. is what youre trying to do while($r = mysql_query($q)) { $emails[]= $r['email']; } $emails = implode(',',$emails); Link to comment https://forums.phpfreaks.com/topic/81965-getting-a-list-of-email-addresses-from-a-database/#findComment-416486 Share on other sites More sharing options...
corbin Posted December 17, 2007 Share Posted December 17, 2007 Ooopppps major typo..... Change the while($r = mysql_query to while($r = mysql_fetch_assoc. Oh, also strlen($emails)-2 should be strlen($emails)-1..... Link to comment https://forums.phpfreaks.com/topic/81965-getting-a-list-of-email-addresses-from-a-database/#findComment-416505 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.