Raphael_b
Raphael_b

Reputation: 1510

PHP: create a list separated by comma

I am trying to create a list of emails separated by coma from a prepared statement.

                $prep_stmt = "SELECT m.email
                                FROM roster_par_membre rm
                                LEFT JOIN membre m 
                                        ON m.id_membre = rm.id_membre                           
                                WHERE id_roster = ? 
                                ";
                $stmt = $mysqli->prepare($prep_stmt);           
                if ($stmt) {
                    $stmt->bind_param('i', $roster_id);
                    $stmt->execute();
                    $stmt->store_result();
                    // get variables from result.
                    $stmt->bind_result($emails_roster);
                    $list = array(); (added)
                    while ($stmt->fetch()){
                        $list[] = $emails_roster;
                    }   
                    $list = implode(',', $list);

The output should be a list of emails without separations. How can I get a list with coma that I can directly use to send an email to this list? At the moment I get a fatal Error: Fatal error: [] operator not supported for strings (for the line inside the while!

Upvotes: 0

Views: 65

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

Try implode:

while ($stmt->fetch()){
   $emails[] = $emails_roster;
}
$emails = implode(',', $emails);

Upvotes: 2

dynamic
dynamic

Reputation: 48091

Not sure if I understood it correctly, but if your $emails_roster contains an email then simply append to an array:

$emails = [];
while ($stmt->fetch()){
 $emails[] = $emails_roster;
}   

print_r($emails); 
echo implode(',', $emails);

Upvotes: 1

Related Questions