dfarrelly dfarrelly - 1 month ago 6
MySQL Question

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: myemail@gmail.com');
}
}

Answer

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 | boss1@boss.com  |
|       1 | boss2@boss.com  |
|       1 | boss3@boss.com  |
|       2 | boris1@boss.com |
|       2 | boris2@boss.com |
+---------+-----------------+

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: myemail@gmail.com');
  }
}
Comments