简体   繁体   English

用PHP发送一封电子邮件,其中包含从数据库中获取的信息

[英]sending an email in PHP with information taken from database

I want to pull an email from the database as the recipient. 我想从数据库中提取一封电子邮件作为收件人。 If I replace the line "SELECT student_user_email FROM students";' 如果我替换"SELECT student_user_email FROM students";' with an actual email address I get the desired outcome. 使用实际的电子邮件地址,我得到了预期的结果。 However it would be handier to pull a particular email address from the 'students' table. 但是,从“学生”表中提取特定的电子邮件地址会比较麻烦。 Below is the current code. 下面是当前代码。 Wondering if anyone can help? 想知道是否有人可以提供帮助?

mail('"SELECT student_user_email FROM students";','Sample Form',$msg, 'From: johnsmith@gmail.com');

First, use mysqli or PDO because the mysql_ functions are depricated. 首先,使用mysqli或PDO,因为mysql_函数已被描述。 The documentation has very useful information to get started with it. 该文档包含非常有用的信息,以帮助您入门。

mysqli: http://php.net/manual/en/book.mysqli.php mysqli: http : //php.net/manual/zh/book.mysqli.php
pdo: http://us3.php.net/pdo pdo: http//us3.php.net/pdo
mail: http://us3.php.net/manual/en/function.mail.php 邮件: http//us3.php.net/manual/en/function.mail.php

This is what you need to do to connect to your database (from the php documentation: http://www.php.net/manual/en/mysqli.quickstart.connections.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;
}

Once connected you can query the database: 连接后,您可以查询数据库:

$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');
    }
}

You can't send email to a multiple recipients in this way. 您不能通过这种方式将电子邮件发送给多个收件人。 Because query return array list so you must be looping and send email one by one recipients by this following way, 因为查询返回数组列表,所以您必须循环并通过以下方式一一发送收件人的电子邮件,

Try this will work: 试试这个将工作:

<?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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM