Reputation:
I am trying to figure out how to put a mysql query result into an array that can be accessed outside the while loop. Is this possible?
My test code that I am playing with is below. I want to send email to the email addresses in the array without creating the email code inside the while loop. That way I can inject the array result into the BCC field and it all goes out at once using the mail() function rather than opening a new smtp connection for each email - or so I think.
<?php
if(isset($_POST['btnSendToSelected']) && isset($_POST['checked']))
{
$checked = array_map('intval',$_POST['checked']);
$email_list = implode(", ", $checked);
$get_emails = mysqli_query($conn, "SELECT UserName, Email FROM users WHERE UserId IN ($email_list)")
or die($dataaccess_error);
while($row = mysqli_fetch_array($get_emails))
{
$emails = array($row['Email']);
$emails_array = implode(", ", $emails);
}
// send the email here outside the while loop...
}
elseif(isset($_POST['btnSendToSelected']) && !isset($_POST['checked']))
{
$msg = $msg_error;
}
?>
Upvotes: 2
Views: 12386
Reputation:
$emails_array = array();
while($row = mysqli_fetch_array($get_emails)) {
$emails_array[] = explode(", ", $row['Email']);
}
foreach($emails_array as $value) {
mail_function($value);
}
Or
while($row = mysqli_fetch_array($get_emails)) {
foreach(explode(", ", $row['Email']) as $value) {
mail_function($value);
}
}
Upvotes: 2
Reputation: 57227
$emails_array = implode(", ", $emails);
You can explode
this line wherever you want to get your array.
//EDIT
It looks like that whole while
loop can be handled a bit better. I suggest
$emails = array();
while($row = mysqli_fetch_array($get_emails))
{
$emails[] = $row['Email']."|||".$row['Username'];
}
Then you've got all the info in the $emails
array in one go.
The |||
is just a random delimiter I chose, You could use a comma or something. Alternatively, you could make that entry a 2-d array, something like
$emails[][0] = $row['Email'];
$emails[][1] = $row['Username'];
...although that specific code probably won't work, the idea will. Then, just access it like this:
echo "Username 99 is ".$emails[99][1];
Upvotes: 4
Reputation: 10191
The email is still stored in the variable $row. And $email... You can also do this:
while($row = mysqli_fetch_array($get_emails))
{
mail($row['Email'],$subject,$message,$headers);
}
If you want to store the emails in an array:
$emails = array();
while($row = mysqli_fetch_array($get_emails))
{
$emails[] = $row['Email'];
}
Upvotes: 1