I have a form that sends email and this all works fine but now I want to send the email to an address that is stored in a mysql database but I can't figure out how to do this. No matter what I try to make '$to' in the mail script below semd to the variable pulled from the database it does not work. Can anyone tell what am I doing wrong? Thanks.
/// 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>';
}
}
?>