0

I have a database tabe:

ID    email

I call this data from the database and post it on a html table:

<?php
  $sql = $link->query("SELECT ...");
  while($data = $sql->fetch_object){
?>

<table>
  <tr>
    <td>
      <?=$data->ID?>
    </td>
    <td>
      <?=$data->email?>
    </td>
    <td>
      <input type="checkbox" id="mail_<?=$data->ID?>">
    </td>
  </tr>
</table>

<?php
  }
?>

<input type="button" id="send_mail_button">

The last column has a checkbox. If this chechbox is checked, when I click on send_mail_button, I'd like to send a mail to every email where the checkbox is checked: to me it's the same if this will be done with an AJAX call either with a form post.

I'm able to do this with:

$subject = 'something';
$body = 'hello world!';

foreach($to as $t){
    mail($t, $subject, $body);
}

but I'm not able to create an array ($to) with all the email address and then retrive every email with a foreach loop where I send the mails.

How can I do it?

Perocat
  • 1,481
  • 7
  • 25
  • 48
  • Using an array would work. Already answered here: http://stackoverflow.com/questions/4997252/get-post-from-multiple-checkboxes – KC135Q Aug 30 '13 at 12:33

3 Answers3

1

I might be a ways off with this answer (I haven't used checkboxes for a long long time), but I am pretty sure that you need to use the name='zzzz' (not id) in the checkbox entry, and secondly, you will need to enter a value for it.

Something like this:

<input type="checkbox" id="something" name="ids[]" value="<?php=$data->email?>">

then in your php code you can do something along the lines of:

foreach ($_POST['ids'] as $thisID)
{
    // you now do what you need to do using the ID
}

This is because checkboxes are actually an array, and you can step through each one individually using the foreach statement.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
1

You mean something like this:

<input type="checkbox" name="emails[]" value="mail_<?=$data->ID?>">

foreach($_POST['emails'] as $email)
{
    $getid = explode('_', $email);
    $email_id = $getid[1];
    // dsth
}
Lkopo
  • 4,798
  • 8
  • 35
  • 60
1

Why not use

<input type="checkbox" name="mail[]" value="<?=$data->email?>">

And then in your forearch do this:

foreach($_POST['to'] as $t){
    mail($t, $subject, $body);
}

On a sidenote, when used on a public envoirement this is bad practice since it does not do any checks and enables users to inject e-mail addresses in your script.

An alternate solution would be:

<input type="checkbox" name="mail[]" id="<?=$data->ID?>">

Then, after submission run another query to retrieve all related e-mail adresses:

$query = "SELECT * FROM emails WHERE ID IN (".mysql_real_escape_string(implode(",",$_POST['mail'])).")";
riekelt
  • 510
  • 3
  • 13