简体   繁体   中英

Query MySQL for an email address and send an email to that address

I am trying to retrieve an email address from a table where the username is a known value. That value will be passed from the previous page but I have made it a constant in this example.

I don't know how to give the result a variable name and call that variable later for the "To" address.

Any help is appreciated.

<?php
    $servername = "xxxx";
    $username = "xxxx";
    $password = "xxxx";
    $dbname = "xxxx";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $SLT_YeerLead = "B.Baggins";

    $sql = "SELECT YeerLeadMail FROM t_staffyeerlead WHERE YeerLead='$SLT_YeerLead'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    echo "" . $row["YeerLeadMail"]. "";
    }
    } else {
    echo "0 results";
    }
    $conn->close();

    echo "<br><br>";

    $to = "??????????????";
    $subject = "Subject";
    $message = "blah blah blah<br><br>";
    $header = "From: administrator@mail.com \r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-type: text/html\r\n";
    $retval = mail ($to,$subject,$message,$header);
    if( $retval == true )
    {
    echo "An E-Mail was sent to the Year Lead <b>$SLT_YeerLead</b><br><br>";
    }
    else
    {
    echo "An E-Mail could not be sent to the Year Lead <b>$SLT_YeerLead</b><br><br>";
    echo "<br><br><br><br><br><br>";
    echo "<b>Please contact ICT Support</b><br><br>";
    echo "Call XXXX<br><br>";
    echo "E-Mail: help@mail.com<br><br>";
    }

    mysql_close($con); ?>

Thanks

Declare the $email inside the while loop as you only have a one row result and assign it to the $to or declare and assign it for cleaner code.

if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "" . $row["YeerLeadMail"]. ""; $email = $row["YeerLeadMail"]; }

$to = $email;

or

if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo "" . $row["YeerLeadMail"]. ""; $to = $row["YeerLeadMail"]; }

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