开发者

PHP: Send an email with the data the user filled in a form, only after the user hit "send"? (the data is an array)

I´m very newbie on PHP, and programming in general, and I´m still reading my manual. I´m trying some excercises, and creating some simple tests of my own.

I have a form, with some checkboxes and select items. The user complete the form and it shows some output. It´s like a little game, where the user selects some answers, and the scripts shows a number that´s his/her score.

Now, I would like to receive an email each time a user completes the game, with all the answers.

The users completes some checkboxes and select items, so, all answers are arrays (So, I´ve tried $message_answer2 = $_POST['answer2']; and it won´t work).

So, I´ve tried:

$to   = 'myown@mail.com';
$subject = 'New Game '.date("m/d/Y h:m:s");
$message_answer2 = join(', ', $_POST['answer2']);
mail($to, $subject, $message_answer2);

There are 2 issues with this:

  • Th开发者_如何学运维ere´s a PHP error that appears: Warning: join() [function.join]: Invalid arguments passed in ...

  • An email is dispatched (a blank email) each time I just reload the page. The emails should be sent only after the user hits the "send" button of the form.

I would really appreciate if someone could help me out with this :)

Thanks!!

Rosamunda


You should try this:

if (isset($POST['answer2'])) {
    $to   = 'myown@mail.com';
    $subject = 'New Game '.date("m/d/Y h:m:s");
    $message_answer2 = join(', ', $_POST['answer2']);
    mail($to, $subject, $message_answer2);
}

I'm assuming when the user submits the form you're having it post to the current page. If that's the case then when you're originally loading the page there is no data set in $_POST['answer2'] which is why you're getting an error, and then its sending the blank message because there is no data to send. Adding that an email will be sent only if statement will make it so that only if there is data being posted to the page in 'answer2'.


join() is for use on arrays. Unless you've used the PHP-specific array notation on your form's field names <input name="answer2[]">, PHP will NOT make $_POST['answer2'] an array - it'll just be an ordinary string.

If your form looks like

<input name="answer2" ...>
<input name="answer2" ...>

then you're still only get a single string value in $_POST. You must use the [] notation to tell PHP it should create an array and add each individual answer2 to that array. When not in array mode, PHP will simply overwrite $_POST['answer2'] with each answer2 value it finds in the form data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜