Page 1 of 1

Undefined index issues on radio buttons and checkbox - help

Posted: Thu Mar 01, 2012 3:33 pm
by bytephp
Hi,

I've got a form which captures data into a MySQL database. Trouble is my radio buttons and checkbox both cause undefined index error messages and I don't know how to stop them from happening. Futhermore, for some reason I need to define things twice otherwise it causes undefined index error messages as well, hence why you see $NAME = cleanInput($_POST['NAME'], $conn); for example near the top of the code and then further down under the // Sanitise details comment.

Really unsure how to fix these, so any help would be appreciated. For my checbox I dont need it to write anything to my database, just needs to see if its checked then allow the form to be submitted, otherwise show the error message.

The radio buttons and checkbox are the last two rows in my form table called "OVER18" and "TERMS".

Code: Select all

<?php
require_once('db.php');
require_once('functions.php');
// date
$DATE = date(cleanInput("Y-m-d", $conn));

$errors = array();

// If request is a form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $NAME = cleanInput($_POST['NAME'], $conn);
    $EMAIL = cleanInput($_POST['EMAIL'], $conn);
    $COMMENTS = cleanInput($_POST['COMMENTS'], $conn);
    $OVER18 = cleanInput($_POST['OVER18'], $conn);
    $TERMS = cleanInput($_POST['TERMS'], $conn);


// Validation
// Check NAME is not less than 2 characters
    if (strlen($NAME) < 2) {
        $errors['NAME'] = "Your name is not long enough";
    }

    // Check TELEPHONE is valid
    if (0 === preg_match("/^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$/", $_POST['TELEPHONE'])) {
        $errors['TELEPHONE'] = "Please enter valid phone number";
    }

    // Check EMAIL is not less than 2 characters
    if (strlen($EMAIL) < 2) {
        $errors['EMAIL'] = "Your email address is not long enough";
    }

    // Check COMMENTS is not less than 3 characters
    if (strlen($COMMENTS) < 3) {
        $errors['COMMENTS'] = "Please enter a comment";
    }

    // Check OVER 18
    if( !isset($_POST['radio']) || ($_POST['radio'] != 'yes' && $_POST['radio'] != 'no') ) {
   $errors['radio'] = 'Please answer this question';
    } 

    // Check TERMS have been agreed
    if ($TERMS == "No") {
        $errors['TERMS'] = "It is required of you to agree to the terms before continuing";
    }

    // If no validation errors
    if (0 === count($errors)) {

        // Sanitise details
        $NAME = cleanInput($_POST['NAME'], $conn);
        $TELEPHONE = cleanInput($_POST['TELEPHONE'], $conn);
        $EMAIL = cleanInput(trim($_POST['EMAIL']), $conn);
        $COMMENTS = cleanInput($_POST['COMMENTS'], $conn);
        $OVER18 = cleanInput($_POST['OVER18'], $conn);
        $TERMS = cleanInput($_POST['TERMS'], $conn);

        // Insert user into the database
        $query = "
    INSERT INTO
        testform  (
            DATE
          , NAME
          , TELEPHONE
          , EMAIL
          , COMMENTS
          , OVER18
          , TERMS
    ) VALUES (
            '$DATE'
          , '$NAME'
          , '$TELEPHONE'
          , '$EMAIL'
          , '$COMMENTS'
          , '$OVER18'
          , '$TERMS'
          )";


        // for debugging
        print_r($_POST);

        $result = mysqli_query($conn, $query) or die(mysqli_error($conn) . $query);

        if ($result != FALSE) {
            // Form submitted successfully
            header("Location: thankyou.php");
            exit;
        }
    }
} else {

    //  DEBUGGING ONLY - DISABLE IN PRODUCTION SITE
    // echo "<br/><br /> MySQLi Error: " . mysqli_error($conn);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
  <table class="form">
    <tr class="<?php echo form_row_class("NAME", $errors); ?>">
      <th><label for="NAME">Telephone</label></th>
      <td><input name="NAME" id="NAME" type="text" value="<?php echo isset($_POST['NAME']) ? hsc($_POST['NAME']) : ''; ?>" />
        <?php echo error_for("NAME", $errors); ?></td>
    </tr>
    <tr class="<?php echo form_row_class("TELEPHONE", $errors); ?>">
      <th><label for="TELEPHONE">Telephone</label></th>
      <td><input name="TELEPHONE" id="TELEPHONE" type="text" value="<?php echo isset($_POST['TELEPHONE']) ? hsc($_POST['TELEPHONE']) : ''; ?>" />
        <?php echo error_for("TELEPHONE", $errors); ?></td>
    </tr>
    <tr class="<?php echo form_row_class("EMAIL", $errors); ?>">
      <th><label for="EMAIL">Email Address</label></th>
      <td><input name="EMAIL" id="EMAIL" type="text" value="<?php echo isset($_POST['EMAIL']) ? hsc($_POST['EMAIL']) : ''; ?>" />
        <?php echo error_for("EMAIL", $errors); ?></td>
    </tr>
    <tr class="<?php echo form_row_class("COMMENTS", $errors); ?>">
      <th><label for="COMMENTS">Comments</label></th>
      <td><textarea name="COMMENTS" id="COMMENTS"><?php echo isset($_POST['COMMENTS']) ? hsc($_POST['COMMENTS']) : ''; ?></textarea>
        <?php echo error_for("COMMENTS", $errors); ?></td>
    </tr>
    <tr class="<?php echo form_row_class("OVER18", $errors); ?>">
      <th><label for="OVER18">Over 18?</label></th>
      <td colspan="2"><label for="OVER18_YES">Yes</label>
        <input type="radio" name="OVER18" id="OVER18_YES value="yes" <?php echo isset($_POST['OVER18']) && $_POST['OVER18'] == 'yes' ? 'checked="checked"' : ''; ?>/>
        <label for="OVER18_NO">NO</label>
        <input type="radio" name="OVER18" id="OVER18_NO" value="no" <?php echo isset($_POST['OVER18']) && $_POST['OVER18'] == 'no' ? 'checked="checked"' : ''; ?>/>
        <?php echo error_for("OVER18", $errors); ?></td>
    </tr>
    <tr class="<?php echo form_row_class("TERMS", $errors); ?>">
      <th><label for="TERMS">Tick box to agree to terms and conditions</label></th>
      <td colspan="2"><input type="checkbox" name="TERMS" id="TERMS" value="Agreed" <?php echo isset($_POST['TERMS']) && $_POST['TERMS'] == 'Agreed' ? 'checked="checked"' : ''; ?>/>
        <?php echo error_for("TERMS", $errors); ?></td>
    </tr>
    <tr>
      <th></th>
      <td><input type="submit" value="Go!" /></td>
    </tr>
  </table>
</form>
</body>
</html>

Re: Undefined index issues on radio buttons and checkbox - h

Posted: Thu Mar 01, 2012 3:48 pm
by social_experiment

Code: Select all

<?php $NAME = cleanInput($_POST['NAME'], $conn); ?>
Using isset() should solve the problem of "double defining" of these variables. As for the checkboxes; are you refering to this code below

Code: Select all

<input type="radio" name="OVER18" id="OVER18_NO" value="no" <?php echo isset($_POST['OVER18']) && $_POST['OVER18'] == 'no' ? 'checked="checked"' : ''; ?>/>
If i'm not mistaken $_POST['OVER18'] will have a value (of 'no') if it is set so you can probably remove the && conditional part of the statement.

Re: Undefined index issues on radio buttons and checkbox - h

Posted: Thu Mar 01, 2012 4:16 pm
by bytephp
Hi social_experiment,

Ah ok, so by using isset would it look like this?

Code: Select all

    if (!isset($_POST['$NAME']) || (strlen($NAME) < 2)) {
        $errors['NAME'] = "Your name is not long enough";
}  
Ok I see, so for the radio button it should look like this then?

Code: Select all

<input type="radio" name="OVER18" id="OVER18_NO" value="no" <?php echo isset($_POST['OVER18']) ? 'checked="checked"' : ''; ?>/>

Re: Undefined index issues on radio buttons and checkbox - h

Posted: Fri Mar 02, 2012 12:15 am
by social_experiment
I looked at the script again; for the second part of the script you could try wrapping the code that executes when the form is submitted in this if statement

Code: Select all

<?php if (isset($_POST['submitButton'])) {
 // execute code
} ?>
This will mean the code is only parsed once the button has been clicked. Note: you will have to add name="submitButton" as an attribute for the submit button on the form.
bytephp wrote:Ok I see, so for the radio button it should look like this then?
Yes

Re: Undefined index issues on radio buttons and checkbox - h

Posted: Sun Mar 04, 2012 3:52 pm
by bytephp
Thanks :D

Also, if I wanted an email to automatically be sent to the user once they filled out the form, would I add it in this section?

Code: Select all

if ($result != FALSE) {
            // Form submitted successfully
            header("Location: thankyou.php");

// Add email to user PHP code here???
            exit;
        }
Futhermore, I assumme it would look something like this?

Code: Select all

<?php
$to = "$EMAIL";
$subject = "Thankyou";
$message = "Hello $NAME. Thank you for completing the form.";
$from = "me@example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?> 

Lastly, can I format the email so I can have a header image, footer and add styling to it just like you would with any email? How would this fit into the code? I've googled it but couldnt see example with images etc in.

Re: Undefined index issues on radio buttons and checkbox - h

Posted: Sun Mar 04, 2012 4:02 pm
by social_experiment
bytephp wrote:Also, if I wanted an email to automatically be sent to the user once they filled out the form, would I add it in this section?
Yes, try sending the mail message before calling the header() function
bytephp wrote:Lastly, can I format the email so I can have a header image, footer and add styling to it just like you would with any email?
You can; you need the following headers when sending the email; then you can style the mail.

Code: Select all

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
Have a look at this url as well;
http://www.php.net/manual/en/function.mail.php

Re: Undefined index issues on radio buttons and checkbox - h

Posted: Mon Mar 05, 2012 11:39 am
by bytephp
Thanks :D

I tired wrapping my code in the isset to get rid of the undefined indexes but no luck unfortunatly. Any idea what else to try?

Code: Select all

<?php if (isset($_POST['submitButton'])) {
 // execute code
} ?>

Re: Undefined index issues on radio buttons and checkbox - h

Posted: Mon Mar 05, 2012 3:26 pm
by social_experiment

Code: Select all

<?php
 isset($_POST['submitButton'])) { 
 // code
 }
?>
This will only work on the submit button; any other undefined values have to be checked individually

Re: Undefined index issues on radio buttons and checkbox - h

Posted: Mon Mar 05, 2012 3:46 pm
by bytephp
Ok thanks. I'm just unsure how this would tie in with the validation part thats all. Would it be a case of editing this part of the code for example?

Code: Select all

    // Check COMMENTS is not less than 3 characters
    if (strlen($COMMENTS) < 3) {
        $errors['COMMENTS'] = "Please enter a comment";
    }
Or would I need to add it somewhere else? And if so would it be something like this? Just not sure where or how this would go. Sorry for all the question, just a bit lost.

Code: Select all

     isset($_POST[COMMENT])) {

 }

Re: Undefined index issues on radio buttons and checkbox - h

Posted: Tue Mar 06, 2012 12:26 am
by social_experiment
No problem :) The undefined notice message will also give a line number showing you where the variable is in the script; that's where you have to change it.

Code: Select all

<?php $NAME = cleanInput($_POST['NAME'], $conn); ?> 
The notices won't affect validation, the message is returned because when you define $NAME, another value, is not set

Can you post one of the notice messages?

Re: Undefined index issues on radio buttons and checkbox - h

Posted: Wed Mar 07, 2012 3:56 pm
by bytephp
I've managed to figure it out, mainly was around checking if the variable were set which is something you covered previously but guess I wasn't doing it correctly. Also for radio buttons and checkbox it was in my validation i needed to check if empty which solved it.

Thanks for your help social_experiment, couldnt have got there without out your help :D