为什么mime在标题中打印而无法调用变量?

时间:2014-03-26 14:12:29

标签: php email mime

假设我有一个班级,例如:

class User{
     function callname(){
         $user = $_SESSION['id'];
         $query = ("SELECT * FROM user WHERE user.id='$user'");
         while ($result=mysql_fetch_array($query)){
              echo ($result['username']);}}}

然后,为User对象创建实例:

$user = new User;

发送邮件的代码:

if($_SERVER["REQUEST_METHOD"] == "POST"){
$username = trim($_POST['username']);
$check = mysql_num_rows(mysql_query("SELECT * FROM user WHERE username='$username'"));

if ($check==TRUE){
    $name = $user->callname();
    $to = "myemail@domain.com";
    $subject = "Example Subject";
    $headers = "From: My Domain".'\r\n'.
      "MIME-Version: 1.0".'\r\n'.
      "Content-Type: text/html; charset=ISO-8859-1".'\r\n'.
      'X-Mailer: PHP/' . phpversion();
    $message = "Hai $name, this is the new message.";

            mail($to, $subject, $message, $headers);
} else {
    ?>
        <script type="text/javascript">
            alert("Sorry, username not exist !");
        </script>
        <?php
}

}

邮件功能正常,我也收到了一封电子邮件。问题是

  1. $name没有在电子邮件中打印用户名。我已经在$name = $user->callname();的不同页面上尝试了这个if()而且它正在运行。

  2. \r\nMIME-Version: 1.0依旧在From标题中打印。

1 个答案:

答案 0 :(得分:1)

  1. 我认为你需要return $result['username']而不是回应它。
  2. 对于特殊字符,您需要使用双引号(&#34;)。
  3. 尝试更正您的代码:

    class User{
         function callname(){
             $user = $_SESSION['id'];
             $query = mysql_query("SELECT * FROM user WHERE user.id='$user'");
             while ($result=mysql_fetch_array($query)){
                  return $result['username'];}}}
    

    下一部分:

    if($_SERVER["REQUEST_METHOD"] == "POST"){
    $username = mysql_real_escape_string(trim($_POST['username']));
    $check = mysql_num_rows(mysql_query("SELECT * FROM user WHERE username='$username'"));
    
    if ($check==TRUE){
        $name = $user->callname();
        $to = "myemail@domain.com";
        $subject = "Example Subject";
        $headers = "From: My Domain"."\r\n".
          "MIME-Version: 1.0"."\r\n".
          "Content-Type: text/html; charset=ISO-8859-1"."\r\n".
          'X-Mailer: PHP/' . phpversion();
        $message = "Hai $name, this is the new message.";
    
                mail($to, $subject, $message, $headers);
    } else {
        ?>
            <script type="text/javascript">
                alert("Sorry, username not exist !");
            </script>
            <?php
    }