我想从数据库中提取一封电子邮件作为收件人。如果我用实际的电子邮件地址替换行"SELECT student_user_email FROM students";'
,我会得到所需的结果。但是,从“学生”表中提取特定的电子邮件地址会更方便。以下是当前代码。想知道是否有人可以提供帮助?
mail('"SELECT student_user_email FROM students";','Sample Form',$msg, 'From: johnsmith@gmail.com');
答案 0 :(得分:1)
首先,使用mysqli或PDO,因为mysql_
函数已被删除。该文档提供了非常有用的信息以便开始使用它。
mysqli:http://php.net/manual/en/book.mysqli.php
pdo:http://us3.php.net/pdo
邮件:http://us3.php.net/manual/en/function.mail.php
这是连接数据库所需要做的事情(来自php文档:http://www.php.net/manual/en/mysqli.quickstart.connections.php)
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
连接后,您可以查询数据库:
$result = $mysqli->query("SELECT student_user_email FROM students");
while ($row = $result->fetch_object()) {
if (isset($row->student_user_email)) {
mail($row->student_user_email,'Sample Form',$msg, 'johnsmith@gmail.com');
}
}
答案 1 :(得分:0)
您无法以这种方式向多个收件人发送电子邮件。因为查询返回数组列表所以您必须通过以下方式循环并逐个发送电子邮件,
试试这个会起作用:
<?php
$con = mysqli_connect("localhost", "uname", "password");
if (!$con){
die('Could not connect: ' . mysqli_error());
}
$db_selected = mysqli_select_db("database",$con);
$sql = "SELECT student_user_email FROM students";
$result = mysqli_query($sql,$con);
while ($row_data = mysqli_fetch_array($result)) {
// Then you will set your variables for the e-mail using the data
// from the array.
$from = 'you@yoursite.com';
$to = $row_data['email']; // The column where your e-mail was stored.
$subject = 'Sample Form';
$msg = 'Hello world!';
mail($to, $subject, $msg, $from);
}
?>