merli
merli

Reputation: 25

Why is mime print in header and can't call a variable?

Let say I have a class, for example:

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

And then, make instance for User object:

$user = new User;

Code to send mail:

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 = "[email protected]";
    $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
}

}

Mail function was working correctly and I have received an email too. The problem is

  1. $name didn't print the name of user in the email. I've tried this $name = $user->callname(); on different page without the if() and it was working.

  2. \r\nMIME-Version: 1.0 and so on was print in the From header.

Upvotes: 0

Views: 57

Answers (1)

Jonas &#196;ppelgran
Jonas &#196;ppelgran

Reputation: 2747

  1. I think you need to return $result['username'] instead of echoing it.
  2. For special characters be read as such you need them in double quotes (").

A attempt to correct your code:

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'];}}}

Next part:

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 = "[email protected]";
    $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
}

Upvotes: 1

Related Questions