Dfarrelly
Dfarrelly

Reputation: 755

Send email to multiple addresses from database

I am trying to make a little contact form, in which I can send an email to multiple users in a database, I am trying to just select all the emails then use a while loop to send to each one, however it is only sending to the first email in my database and not the rest.. I can't figure out where I'm going wrong

if(isset($_POST['submit'])) {
  $body= $_POST['body'];
  $subject= $_POST['subject'];
  $user = $_SESSION["name"];

  $sql = "SELECT * FROM $user";
  $result = $conn->query($sql);

  while($row = mysqli_fetch_array($result)){
      $email = $row["contact_email"];
      mail($email, $subject, $body,'From: [email protected]');
  }
}

Upvotes: 1

Views: 1670

Answers (1)

Cristofor
Cristofor

Reputation: 2097

Assuming you have the following tables:

Users

+----+-------+
| id | name  |
+----+-------+
|  1 | Boss  |
|  2 | Boris |
+----+-------+
create table users(
 id int auto_increment primary key,
 name varchar(255) not null
);

Emails

+---------+-----------------+
| user_id |      email      |
+---------+-----------------+
|       1 | [email protected]  |
|       1 | [email protected]  |
|       1 | [email protected]  |
|       2 | [email protected] |
|       2 | [email protected] |
+---------+-----------------+

create table emails(
 user_id int references users(id),
 email varchar(255) not null
);

Pay attention to the reference that the user_id has to the users table.

Now in PHP

if(isset($_POST['submit'])) {
  $body = $_POST['body'];
  $subject = $_POST['subject'];
  $user = mysqli::real_escape_string($_SESSION["name"]);

  $result = $conn->query("SELECT id from users where name='".$user."'");
  $row = mysqli_fetch_array($result);
  $user_id = intval($row["id"]);

  $sql = "SELECT email FROM emails where user_id=".$user_id;
  $result = $conn->query($sql);

  while($row = mysqli_fetch_array($result)){
      $email = $row["email"];
      mail($email, $subject, $body,'From: [email protected]');
  }
}

Upvotes: 1

Related Questions