简体   繁体   中英

PHP - email to email address based on database query

i am trying to create a reply to an ad form where a user clicks an ad and can send an email, however i do not want the users to actually see which address they are sending it to but instead the email address can be taken from a database based on the username of the ad

i have tried this code but cant seem to get it to work, any help appreciated!

$username = $_SESSION['username'];

$sql = "SELECT * FROM user WHERE username=:username";
$q = $conn->prepare($sql);
$q->bindParam(':username', $username, PDO::PARAM_STR);
$q->execute();
$row = $q->fetch(PDO::FETCH_ASSOC);

$email1 = $row['email']; 

 $to='$email1';
$messageSubject='Message subject';
$confirmationSubject='Confirmation message subject';
$confirmationBody="Confirmation message body";
 $email='';
  $body='';
$displayForm=true;
if ($_POST){
$email=stripslashes($_POST['email']);
$body=stripslashes($_POST['body']);
// validate e-mail address
$valid=eregi('^([0-9a-z]+[-._+&])*[0-9a-z]+@([-0-9a-z]+[.])+[a-z]{2,6}$',$email);
$crack=eregi("(\r|\n)(to:|from:|cc:|bcc:)",$body);
if ($email && $body && $valid && !$crack){
  if (mail($to,$messageSubject,$body,'From: '.$email."\r\n")
      && mail($email,$confirmationSubject,$confirmationBody.$body,'From: '.$to."\r\n")){
    $displayForm=false;

Don't use the ereg functions. They're deprecated and have serious issues. Use preg instead.

To answer your question, this should be simply

$to = $email1;

or better yet, skip that stage and do

$email1 = $row['email1'];

With the ' single quotes, you're forcing PHP to treat $email1 as a string, not as a variable. so you're trying to send to an address named $email1 , not the contents of the $email1 variable.

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