[英]Sending email to email address retrieved from database Initiated by session in PHP
[英]sending an email in PHP with information taken from database
我想從數據庫中提取一封電子郵件作為收件人。 如果我替換"SELECT student_user_email FROM students";'
使用實際的電子郵件地址,我得到了預期的結果。 但是,從“學生”表中提取特定的電子郵件地址會比較麻煩。 下面是當前代碼。 想知道是否有人可以提供幫助?
mail('"SELECT student_user_email FROM students";','Sample Form',$msg, 'From: johnsmith@gmail.com');
首先,使用mysqli或PDO,因為mysql_
函數已被描述。 該文檔包含非常有用的信息,以幫助您入門。
mysqli: http : //php.net/manual/zh/book.mysqli.php
pdo: http : //us3.php.net/pdo
郵件: http : //us3.php.net/manual/en/function.mail.php
這是您需要執行的操作,以連接到數據庫(來自php文檔: http : //www.php.net/manual/zh/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');
}
}
您不能通過這種方式將電子郵件發送給多個收件人。 因為查詢返回數組列表,所以您必須循環並通過以下方式一一發送收件人的電子郵件,
試試這個將工作:
<?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);
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.