Reputation: 25
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
$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.
\r\nMIME-Version: 1.0
and so on was print in the From header.
Upvotes: 0
Views: 57
Reputation: 2747
return $result['username']
instead of echoing it.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