I'm creating a web page where users can create posts. Other users can reply to the post by filling out a form which sends an email to the post creator. I iterate with while loop to show all posts from MySQL db and at the same time show form for replying.
The problem I'm having is, when I press the send button on the reply form, all users from the db gets an email. The way it should work is, the person I'm replying to should get the email. Tried other iterators. Thinking about using objects but just can't understand why when I press the send button mail() function sends an email to all users.
$query = mysql_query("SELECT * FROM msg ORDER by id DESC");
while ($row = mysql_fetch_array($query)){
print '<div class="block">
<div id="uMail">
<a id="mail" href="'.$row['userMail'].'"> <img src="mail.png" > </a>
</div>
<div id="uName">
<span id="var">'.$row['userName'].'</span>
</div>
<div id="uMsg">
<p>'.$row['userMsg'].'</p>
</div>
</div>
<div class="popup">
<form action="" method="POST">
<div id="sName">
<input type="text" name="sName" />
</div>
<div id="sMail">
<input type="email" name="sMail" />
</div>
<textarea name="sMsg"></textarea>
<input type="submit" name="send" value="Send" />
</form>
</div>
';
if (isset($_POST["send"])) {
$usrMail = $row['userMail'];
$sndrName = mysql_real_escape_string($_POST["sName"]);
$sndrMail = mysql_real_escape_string($_POST['sMail']);
$sndrMsg = mysql_real_escape_string($_POST["sMsg"]);
mail($usrMail, "Hey", $sndrMsg);
header('location: forma.php');
}
}
Because sendmail() is inside the while().
I highly recommend https://github.com/PHPMailer/PHPMailer for sending E-Mails, because mail() cannot specify a SMTP.
Well you are redirecting the user to forma.php after sending one email. You should move this line:
header('location: forma.php');
outside the while loop, so the user is redirected after all emails are sent
so finally i made it, i just made submit button name as $i, which is $i++ in while cycle. then i made if(isset($_POST["$i"])) inside while with mail function and its working :) But, now i want to make popup form for answering and have no idea how to manage it :)