如何将电子邮件发送到我的数据库中的地址


How to send an email to an address from my database?

我有一个发送电子邮件的表单,这一切都很好,但现在我想将电子邮件发送到存储在mysql数据库中的地址,但我不知道如何做到这一点。无论我试图在semd下面的邮件脚本中为从数据库中提取的变量设置"$to",它都不起作用。有人能说出我做错了什么吗?谢谢

/// Get get recipients email address from database using id
$id= $_GET["id"];
$result = mysqli_query($conx, "SELECT email from mytable where id='$id'");
while($row = mysqli_fetch_array($result)) {
$to = $row["email"];
}
    if ($_GET["submit"]) {  
        $name =  htmlspecialchars($_GET['name']);
        $email = htmlspecialchars($_GET['email']);
        $message = $_GET['message'];
        $subject = 'Hello There';
        $body = "E-Mail: $email'n Message: $message";
        if (mail($to, $subject, $body)) {
        $result='<div class="alert alert-success">Your email has been sent</div>';
             }else{
        $result='<div class="alert alert-danger">Sorry there was an error sending your message.</div>';
    }
}
?>

您应该尝试以下方式:

要从SQL注入中保护此代码,请阅读本文。

/// Get get recipients email address from database using id
$id= (int) $_GET["id"];
$result = mysqli_query($conx, "SELECT email from mytable where id='$id'");
$row = mysqli_fetch_array($result);
$to = $row["email"];

    if ($_GET["submit"]) {  
        $name =  htmlspecialchars($_GET['name']);
        $email = htmlspecialchars($_GET['email']);
        $message = $_GET['message'];
        $subject = 'Hello There';
        $body = "E-Mail: $email'n Message: $message";
        if (mail($to, $subject, $body)) {
        $result='<div class="alert alert-success">Your email has been sent</div>';
             }else{
        $result='<div class="alert alert-danger">Sorry there was an error sending your message.</div>';
    }
}
?>