John120 John120 - 2 months ago 7x
MySQL Question

How to select all emails from mysql table and assign it to $to of mail function in php?

Actually i want to email to all users so, small problem regarding selection of all emails from MySQL's table in PHP. how can i use select query to select all emails from table and assign them to $to with separating each email with comma. I have tried various things. This doesn't work. I have a table "users" with fields like id,name,email,mobile,address,password.

Any help would be appreciated !

Code :

if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$to = "$allemail";

$headers = "From:$name<$email>";
$message = "Name: $name\n\n Email: $email \n\n Subject : $subject \n\n Message : $comments";
if (mail($to, $subject, $message, $headers)) {
echo "Email Send";
} else {
echo "Error : Please Try Again !";

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);

$sql = "select group_concat(email separator ',') as email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0)

while($row = $result->fetch_assoc())
$allemail =$row["email"];
else {
echo "0 results";

<!DOCTYPE html>
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Mail Document</title>
<form action="" method="post" >
<p>Name :<br>
<input type="text" name="name" id=""></p>
<p>Email :<br>
<input type="text" name="email" id=""></p>
<p>Subject :<br>
<input type="text" name="subject" id=""></p>
<p>Comments :<br>
<textarea name="comments" id="" cols="30" rows="10"></textarea></p>
<p><input type="submit" value="Send Email" name="submit"></p>


use group_concat for it

$query = 'select group_concat(email separator ',') as email FROM users';
if ($result=mysqli_query($con,$query))
  // Fetch one and one row
  while ($row=mysqli_fetch_row($result))
     $to = $row;
  // Free result set

$to will be comma separated pass it to mail function