简体   繁体   中英

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";' 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. The documentation has very useful information to get started with it.

mysqli: http://php.net/manual/en/book.mysqli.php
pdo: http://us3.php.net/pdo
mail: 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 )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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