Quick help with email checkboxes!

Discussion in 'PHP' started by buddingphp, Jun 11, 2008.

  1. #1
    Hi all,

    I'm new to this site and I have a quick question.
    I've had an email contact form for some time and just added some checkboxes. The code works great when I have one or more checkboxes selected. Funny thing is when no checkboxes are selected and I submit the form I get this error:

    Warning: Invalid argument supplied for foreach() in /home/crikle/public_html/allthatmatters/mailer.php on line 11

    I sure its a simple fix that is needed but I can't get my head around this one.
    It looks like the foreach() command is missing something but what?
    Help.

    My code is this:

    <?php
    if(isset($_POST['submit'])) {


    $to = "goodguy@btinternet.com";
    $subject = "Form";
    $name_field = $_POST['name'];
    $email_field = $_POST['email'];
    $message = $_POST['message'];

    foreach($_POST['check'] as $value) {

    $check_msg .= "Checked: $value\n";

    }


    $body = "From: $name_field\n E-Mail: $email_field\n Message: $message\n $check_msg";


    echo "Data has been submitted to $to!";
    mail($to, $subject, $body);


    } else {

    echo "failed";

    }
    ?>
     
    buddingphp, Jun 11, 2008 IP
  2. sky22

    sky22 Guest

    Messages:
    59
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Hello,

    When no checkboxes are selected $_POST['check'] doesn't exist, so so there is no array which causes an error.

    Try:

    
    if( isset($_POST['check']) ) {
    	foreach($_POST['check'] as $value) {
    		$check_msg .= "Checked: $value\n";
    	}
    }
    PHP:
    That makes sure $_POST['check'] exists before letting foreach use it.

    Sky22
     
    sky22, Jun 11, 2008 IP
  3. buddingphp

    buddingphp Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi,

    This worked, thanks.
    if isset was what I needed.
     
    buddingphp, Jun 11, 2008 IP