gpt4 book ai didi

php - 如何从mysql表中选择所有电子邮件并将其分配给php中邮件函数的$to?

转载 作者:行者123 更新时间:2023-11-29 11:20:31 25 4
gpt4 key购买 nike

实际上我想向所有用户发送电子邮件,所以,关于从 PHP 中的 MySQL 表中选择所有电子邮件的小问题。我如何使用选择查询从表中选择所有电子邮件并将它们分配给 $to 并用逗号分隔每封电子邮件。我尝试过各种事情。这是行不通的。我有一个表“用户”,其中包含 ID、姓名、电子邮件、手机、地址、密码等字段。

如有任何帮助,我们将不胜感激!

代码:

<?php
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";
}
$conn->close();
?>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Mail Document</title>
</head>
<body>
<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>
</form>
</body>
</html>

最佳答案

使用 group_concat

$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
mysqli_free_result($result);
}

$to 将以逗号分隔,将其传递给邮件函数

关于php - 如何从mysql表中选择所有电子邮件并将其分配给php中邮件函数的$to?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39015032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com