PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Fri Nov 28, 2014 6:56 am

All times are UTC - 5 hours




Post new topic Reply to topic  [ 11 posts ] 
Author Message
PostPosted: Thu Mar 01, 2012 4:33 pm 
Offline
Forum Newbie

Joined: Tue Feb 28, 2012 2:36 pm
Posts: 13
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".

Syntax: [ Download ] [ Hide ]
<?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>
 


Top
 Profile  
 
PostPosted: Thu Mar 01, 2012 4:48 pm 
Offline
DevNet Master
User avatar

Joined: Sun Feb 15, 2009 12:08 pm
Posts: 2775
Location: .za
Syntax: [ Download ] [ Hide ]
<?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
Syntax: [ Download ] [ Hide ]
<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.

_________________
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering


Top
 Profile  
 
PostPosted: Thu Mar 01, 2012 5:16 pm 
Offline
Forum Newbie

Joined: Tue Feb 28, 2012 2:36 pm
Posts: 13
Hi social_experiment,

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

Syntax: [ Download ] [ Hide ]
    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?

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


Top
 Profile  
 
PostPosted: Fri Mar 02, 2012 1:15 am 
Offline
DevNet Master
User avatar

Joined: Sun Feb 15, 2009 12:08 pm
Posts: 2775
Location: .za
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
Syntax: [ Download ] [ Hide ]
<?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

_________________
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering


Top
 Profile  
 
PostPosted: Sun Mar 04, 2012 4:52 pm 
Offline
Forum Newbie

Joined: Tue Feb 28, 2012 2:36 pm
Posts: 13
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?

Syntax: [ Download ] [ Hide ]
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?

Syntax: [ Download ] [ Hide ]
<?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.


Top
 Profile  
 
PostPosted: Sun Mar 04, 2012 5:02 pm 
Offline
DevNet Master
User avatar

Joined: Sun Feb 15, 2009 12:08 pm
Posts: 2775
Location: .za
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.
Syntax: [ Download ] [ Hide ]
$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

_________________
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering


Top
 Profile  
 
PostPosted: Mon Mar 05, 2012 12:39 pm 
Offline
Forum Newbie

Joined: Tue Feb 28, 2012 2:36 pm
Posts: 13
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?

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


Top
 Profile  
 
PostPosted: Mon Mar 05, 2012 4:26 pm 
Offline
DevNet Master
User avatar

Joined: Sun Feb 15, 2009 12:08 pm
Posts: 2775
Location: .za
Syntax: [ Download ] [ Hide ]
<?php
 isset($_POST['submitButton'])) {
 // code
 }
?>

This will only work on the submit button; any other undefined values have to be checked individually

_________________
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering


Top
 Profile  
 
PostPosted: Mon Mar 05, 2012 4:46 pm 
Offline
Forum Newbie

Joined: Tue Feb 28, 2012 2:36 pm
Posts: 13
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?

Syntax: [ Download ] [ Hide ]
    // 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.

Syntax: [ Download ] [ Hide ]
     isset($_POST[COMMENT])) {

 }
 


Top
 Profile  
 
PostPosted: Tue Mar 06, 2012 1:26 am 
Offline
DevNet Master
User avatar

Joined: Sun Feb 15, 2009 12:08 pm
Posts: 2775
Location: .za
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.

Syntax: [ Download ] [ Hide ]
<?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?

_________________
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering


Top
 Profile  
 
PostPosted: Wed Mar 07, 2012 4:56 pm 
Offline
Forum Newbie

Joined: Tue Feb 28, 2012 2:36 pm
Posts: 13
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


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 11 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: Google [Bot] and 12 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group