SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot
    Join Date
    Jun 2006
    Location
    Australia
    Posts
    189
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Exclamation Testing form with PHP

    Gudday all
    I have finally got my JS validation of a form working but PHP validation is causing me so much grief.
    Here is my bog standard form
    HTML Code:
    <h2>Ordering a catalogue</h2>
    <div style="font-size:11px;">The items marked with a * are essential.</div><br />
    <form method="post" name="catalogue" action="cataloguetest-7.php";">
    <!--<label></label>-->
    <table class="table1" border="0">
    <tr><td>Media type*:</td>
    <td>
    <input type="radio" id="booklet" name="media" value="booklet">Booklet
    <input type="radio" id="CD" name="media" value="CD/DVD">CD/DVD</td>
    </tr>
    <tr><td style="width:90px;"><label>Name*:</label></td><td><input name="name" id="name" type="text" /></td></tr>
    <tr><td><label>Address*:</label></td><td><input name="address" id="address" type="text" /></td></tr>
    <tr><td><label>Ciy/Town*:</label></td><td><input name="city" id="city" type="text" /></td></tr>
    <tr><td><label>State*:</label></td><td><input name="state" id="state" type="text" /></td></tr>
    <tr><td><label>Post Code*:</label></td><td><input name="postcode" id="postcode" type="text" /></td></tr>
    <tr><td><label>Country*:</label></td>
    <td>
    <select name="country" id="country" size="1">
    < .. Country drop down list here ..>
     </select></td></tr>
    <tr><td><label>E-mail*:</label></td><td><input name="email" id="email" type="text" /></td></tr>
    <tr><td><label>Telephone:</label></td><td><input name="phone" id="phone" type="text" /></td></tr>
    </tr>
    </table>
     <br />
     <input name="catalogue" id="catalogue" type="submit" value="Request catalogue">
    </form>
    What I would like the php to do is to test the following
    1. Form submitted with no data at all - re-display form and give submitter message to that effect.
    2. Check each field for data - re-display form and give submitter message to that effect.
    3. If e-mail address invalid - re-display form and give submitter message to that effect.
    No. 2 should be the easiest but even that has me stumped.
    The code below (cataloguetest-7.php) just checks for the submitter's name, address and city but all that is displayed when I press submit is the php code itself.
    PHP Code:
    <?php

       
    //Form has some data entered
       //Init error variables
       
    $errorName  false;
       
    $errorAddress false;
       
    $errorCity  false;
       
    $errorState  false;
       
    $errorPostcode  false;
       
    $errorEmail false
       
       
    $name  = isset($_POST['name'])  ? trim($_POST['name'])  : '';  
       
    $address  = isset($_POST['address'])  ? trim($_POST['address'])  : '';
       
    $city  = isset($_POST['city'])  ? trim($_POST['city'])  : ''
       
    $state  = isset($_POST['state'])  ? trim($_POST['state'])  : '';
       
    $postcode  = isset($_POST['postcode'])  ? trim($_POST['postcode'])  : '';   
       
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';   
       
       
    // Display the form again as there was an error   
       
    if ($errorName || $errorAddress || $errorCity
        {     
          
    header('location: cataloguerequestK.htm');    
          
    //showForm($errorName,$errorEmail,$errorMesg);
        

        else 
        {
          
    $sendto "xyz@abc.com.au"
          
    $subject "Petals & Patches catalogue request"
          
    $message = <<<TEXT
    I would a copy of the Petals & Patches catalogue to be sent to me please -\r\n
    Media: 
    $media\r\n
    Name: 
    $name\r\n
    Address: 
    $address\r\n
    City/Town: 
    $city\r\n
    State: 
    $state\r\n
    Post code: 
    $postcode\r\n
    Country: 
    $country\r\n
    E-mail: 
    $email\r\n
    Telephone: 
    $telephone
    TEXT;
          
    // sending e-mail
          
    mail("$sendto""$subject""$message");
          
    header('Location: thankyou.htm');
          exit();
        }
    ?>
    No doubt he solution is staring me in the face but I have tried so many variations that I must have had the correct code at some stage and not known it. I supect that the major problem is that I am not passing the form fields to the php code correctly. (I am leaving the radio button validation to the very last)

    Help!
    ========================
    Carn the Tiges!
    www.petalsandpatches.com

  2. #2
    SitePoint Zealot zalucius's Avatar
    Join Date
    Jul 2007
    Location
    Denmark
    Posts
    162
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It looks like your "error" variables never change... they will always be false.

    Here is a suggestion, its not a full example, however it should point you in the right direction:
    Code PHP:
    <?php
    if (isset($_POST['catalogue']))
    {
    	$errors = array();
    	$submit_form = true; // assume the form is filled correct.
     
    	// grab the values from the form.
    	$name = trim($_POST['name']);
    	$address = trim($_POST['address']);
    	$email = trim($_POST['email']);
    	// etc...
     
     
    	// test if all fields contain valid data
    	if ($name == '' || strlen($name) < 2) 
    	{	
    		$submit_form = false; // set submit_form to false
    		$errors['name'] = 'Please supply your name.'; // store an error message.
    	}
    	if ($address == '')
    	{
    		$submit_form = false;
    		$errors['adress'] = 'Please supply your address.'
    	}
    	if (!eregi("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)) 
    	{
    		$submit_form = false;
    		$errors['email'] = 'Please provide a valid email';
    	}
    	// etc...
     
    	// if one or more fields did not pass PHP validation
    	// $submit_form will contain false, and the script need to stop
    	if(!$submit_form)
    	{
    		// redisplay the form, with posted data and error messages.
    	}
    	else
    	{
    		// send the mail.
    	}
    }
    ?>
    zalucius

  3. #3
    SitePoint Zealot
    Join Date
    Jun 2006
    Location
    Australia
    Posts
    189
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Dear Zalucius
    Thank you for your reply. I have been fiddling around with that code but without much much success.
    The 1st problem is that when the form is correctly filled out and I choose submit I do not get the thank you message I expect. Instead I get the php code on the screen.
    I am calling the php via the line
    HTML Code:
    <form method="post" name="catalogue" action="cataloguetest-8.php";>
    I have removed the JS portion of my code that called the client-side validation. It looks like
    HTML Code:
    <form method="post" name="catalogue" onsubmit="return valFrm()" action="cataloguetest-8.php";>
    How do we get the code to call both the JS validation and PHP validation? Is the command
    HTML Code:
    action="cataloguetest-8.php"
    correct?
    The 2nd problem I could see (once I get that far!) is how to display the error messages along with the form.
    Is the code below correct as it is and what is missing?
    PHP Code:
    if(!$submit_form)
        {
            
    // redisplay the form, with posted data and error messages.
            
    header('location: cataloguerequestK.htm');
           ... 
    How are the error messages displayed?...
        } 
    ========================
    Carn the Tiges!
    www.petalsandpatches.com

  4. #4
    SitePoint Evangelist Waffles's Avatar
    Join Date
    Nov 2005
    Posts
    435
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    any real reason you need both java and php validation?

    and for displaying the errors, something like

    PHP Code:
    <?
    //..

    if(!$submit_form)
    {
       echo 
    '<p>There were some errors:</p>';
       
    print_r($errors); //add html formatting to the error messages i.e. <br />
    }
    ?>
    edit: if you're doing the form processing on another document, you won't be able to access the $POST variables from the original form again, once you leave the forms action page. (my understanding, likely to be wrong).

    could just do it all on one form:

    PHP Code:
    <?php 
    if(isset($_POST['submit']))
    {
        
    $name=$_POST['name'];
        
    $email=$_POST['email'];
            ..

        if(
    $name == '' || $email == '' || $comments == '')
        {
            
    $error '<p>Sorry, there has been an error. Please try again.';
            
    //or individual field validation

        
    } else { //all validated
            //send the mail
            
    $success TRUE

        }
    }
    if(!
    $success) {

    ?>

    *display the form, you can access $_POST variables here to fill in existing fields values.

    <?php ?>
    Last edited by Waffles; Jul 18, 2009 at 06:06. Reason: tags

  5. #5
    SitePoint Addict
    Join Date
    Apr 2007
    Posts
    300
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Following is a form/processor which will do everything in one page thereby keeping things simple with a single copy. Attached code follows template approach which enables good amount of separation of php from html making things easy to follow. Feel free ask qns if you don't understand any aspects of this code. This is by no means a complete processor but just a sample foundation which can be easily built up.

    PHP Code:
    <?php

    function insertError($name$message)
    {
        
    $error = <<<ERROR
        <tr>
            <td class="error" colspan=2 >
    $message</td>
        </tr>
    ERROR;
        return 
    $error;
    }

    function 
    initError($formFields)
    {
        foreach (
    $formFields as $key => $value)
        {
            
    $error[$value] = null;
        }
        return 
    $error;
    }

    function 
    initData($formFields)
    {
        foreach (
    $formFields as $key => $value)
        {
            
    $data[$value] = null;
        }
        return 
    $data;
    }

    $formFields = array('media''name''address''city''state''postcode''country''email''phone');

    $error initError($formFields);
    $data initData($formFields);
    $formError false;

    if (!empty(
    $_POST))
    {
        foreach (
    $_POST as $key => $value)
        {
            
    $value trim($value);
            if (empty(
    $value))
            {
                
    $formError true;
                
    $error[$key] = insertError($keyucfirst($key) . " field was left empty");
            }

                
    #    MORE VALIDATION TESTS CAN BE ADDED HERE

            
    else
            {
                
    $data[$key] = $value;
            }
        }

        if (isset(
    $formError) and !$formError)    #    CHECK IF THERE WERE ERRORS IN FORM
        
    {
            
    #    IF THERE ARE NO ERRORS START PROCESSING FORM DATA HERE
        
    }

    }


    $form = <<<FORM

    <form method="post" action="request.php">

    <table class="table1" border="0">
        <tr>
            <td>Media type*:</td>
            <td>
                <input type="radio" id="booklet" name="media" value="booklet" /> Booklet
                <input type="radio" id="CD" name="media" value="CD/DVD" /> CD/DVD
            </td>
        </tr>
    ${error['media']}
        <tr>
            <td class="c2"><label>Name*:</label></td>
            <td><input name="name" id="name" type="text" value="
    ${data['name']}" /></td>
        </tr>
    ${error['name']}
        <tr>
            <td><label>Address*:</label></td>
            <td><input name="address" id="address" type="text" value="
    ${data['address']}" /></td>
        </tr>
    ${error['address']}
        <tr>
            <td><label>Ciy/Town*:</label></td>
            <td><input name="city" id="city" type="text" value="
    ${data['city']}" /></td>
        </tr>
    ${error['city']}
        <tr>
            <td><label>State*:</label></td>
            <td><input name="state" id="state" type="text" value="
    ${data['state']}" /></td>
        </tr>
    ${error['state']}
        <tr>
            <td><label>Post Code*:</label></td>
            <td><input name="postcode" id="postcode" type="text" value="
    ${data['postcode']}" /></td>
        </tr>
    ${error['postcode']}
        <tr>
            <td><label>Country*:</label></td>
            <td>
                <select name="country" id="country" size="1">
                </select>
            </td>
        </tr>
    ${error['country']}
        <tr>
            <td><label>E-mail*:</label></td>
            <td><input name="email" id="email" type="text" value="
    ${data['email']}" /></td>
        </tr>
    ${error['email']}
        <tr>
            <td><label>Telephone:</label></td>
            <td><input name="phone" id="phone" type="text" value="
    ${data['phone']}" /></td>
        </tr>
    ${error['phone']}
    </table>

    <input name="catalogue" id="catalogue" type="submit" value="Request catalogue" />

    </form>

    FORM;

    if (empty(
    $_POST) or $formError)
    {
        
    #    RETURNING BACK TO FORM IF THERE WERE ERRORS OR IF THE FORM IS BEING LOADED FOR THE FIRST TIME

    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

    <head>
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
        <meta name="author" content="Peter Selvaraj" />

        <title>Untitled 1</title>
        <style type="text/css">
        
        *    {
            margin: 0;
            padding: 0;
            font-size: 100%;
            font-weight: normal;
        }
        body    {
            padding: 20px;
            font: 65.2% Arial, Helvetica, sans-serif;
        }
        h2    {
            font-size: 1.6em;
            font-weight: bold;
            margin-bottom: 1em;
        }
        form, p    {
            font-size: 1.2em;
            margin-bottom: 1em;
        }
        form *    {
            font-size: 100%;
        }
        input    {
            padding: 3px;
        }
        table    {
            margin-bottom: 20px;
            border-collapse: collapse;
        }
        td    {
            padding: 0.5em 0;
        }
        td.error    {
            color: #f00;
            font-size: 0.9em;
            padding: 0 0 10px 0;
        }
        
        </style>
    </head>

    <body>

    <h2>Ordering a catalogue</h2> 

    <p>The items marked with a * are essential.</p>

    <?php
        
    echo $form;        #    PRINT FORM BLOCK
    ?>

    </body>
    </html>

    <?php
    }
    ?>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •