Home > Back-end >  PHP Single Page Form Processing
PHP Single Page Form Processing

Time:10-20

The desired example output is (on same page):

BEFORE SUBMIT

  • Drop-downs for shirt order (band, size, color, style)

Contact form

  • Name: _
  • Email: _
  • Phone: _
  • Address: _ (including city, state, and zip)
  • Submit/Reset buttons

AFTER SUBMIT

Thank you for your Order!

  • Order info here from drop-downs <example: Large Black AJR Hoodie>

Shipping & Contact Information:

  • Name: _

  • Email: _

  • Phone: _

  • Address: _ (including city, state, and zip)

  • Link to submit another form at the bottom


I am new here so please point me in the right direction if I am misunderstanding how to submit a question here. Also, sorry this is so long.

I am working on a PHP form that has dropdowns for the product selections as well as fields for the customer's information. I need to process this on a single page instead of processing it on a separate page. Therefore, when the information is submitted it needs to process and show the information submitted with a thank you message. In addition, if the form is not filled out completely or the way it needs to be filled out, then an error should show for the field(s) that were incorrect. However, the information that the user entered should still remain.

My work and questions: I have shared my code below (again, sorry it's really long given it is supposed to be all on one page). The issues that I am still having are:

1. I am getting warning errors stating that I have "Undefined array keys". I get this before and after the form has been submitted. I have defined the arrays at the top so I am unsure why they are undefined.

2. The t-shirt drop-down options are not retaining any selected information if selected. I have tried creating the arrays for this information in the form code itself and at the top and can't seem to get it to stick. I have also tried another coding option of echoing out the selected option and putting the selection in the $_POST or the $_GET.

3. My error trapping is not working if I enter an incorrect phone number format. I initially get the error stating to put it in the right format, but if I put the information in the correct format and submit I still get the error and the phone number resets to what it was initially. I am getting that it is pulling it from the $_GET, but not sure why when it is submitted again it is not updating the $_GET to populate it correctly.

4. Lastly, the form and the information that should populate after it has been submitted correctly are showing on the page at the same time. It should be the form until everything is filled out correctly and then the Thank you message with the information submitted below as a confirmation. I have tried putting these both into PHP with an if(empty....) for if the button has not been pushed then echo the form and check for error, and if it has been pushed to check for errors and if there are none display the thank you for submitting info. However, I couldn't get the error trapping to work or to get the form info to stay in the form if not correct.

Any suggestions on how to shorten my code or the format is also welcome. Thank you in advance!

<?php
        //arrays
        $bands = array ("ACDC", "Journey", "Modest Mouse", "Band of Horses", "Vampire Weekend", "Of Monsters and Men", "Broken Bells", "Phoenix", "Fleetwood Mac", "AJR",);
        $colors = array ("Black", "Navy", "Red", "Orange", "Pink", "Yellow", "Green", "Gray", "White", "Purple",);
        $sizes = array ("X-Small", "Small", "Medium", "Large", "X-Large", "XX-Large", "XXX-Large",);
        $styles = array ("Tank Top", "T-Shirt", "Long Sleeve", "Hoodie", "Sweatshirt", "Jacket",);
        
        
        if(isset($_POST['firstName'])) $firstName = $_POST['firstName'];
        if(isset($_POST['lastName'])) $lastName = $_POST['lastName'];
        if(isset($_POST['email'])) $email = $_POST['email'];
        if(isset($_POST['phone'])) $phone = $_POST['phone'];
        if(isset($_POST['address'])) $address = $_POST['address'];
        if(isset($_POST['city'])) $city = $_POST['city'];
        if(isset($_POST['state'])) $state = $_POST['state'];
        if(isset($_POST['zip'])) $zip = $_POST['zip'];
        if(isset($_POST['colors'])) $colors = $_POST['colors'];
        if(isset($_POST['bands'])) $bands = $_POST['bands'];
        if(isset($_POST['sizes'])) $sizes = $_POST['sizes'];
        if(isset($_POST['styles'])) $styles = $_POST['styles'];
        
        $product_vars = array(
        array( 'element_name' => 'band', 'title' => 'Band', 'options' => $bands, 'placeholder' => 'Choose One', ), 
        array( 'element_name' => 'color', 'title' => 'Color', 'options' => $colors, 'placeholder' => 'Choose One', ), 
        array( 'element_name' => 'size', 'title' => 'Size', 'options' => $sizes, 'placeholder' => 'Choose One', ), 
        array( 'element_name' => 'style', 'title' => 'Style', 'options' => $styles, 'placeholder' => 'Choose One', ), 
        );
    
        foreach($product_vars as $cur_product) {
        ?>
                <label><?php echo $cur_product['title']; ?>: </label>
                    <select name="<?php echo $cur_product['element_name']; ?>" size="1">
                        <option><?php echo $cur_product['placeholder']; ?></option>
                        <?php
                            foreach($cur_product['options'] as $cur_option)
                            {
                                echo "<option value = '".$cur_option."' ".(isset($_POST[$cur_product['element_name']]) && $_POST[$cur_product['element_name']] == $cur_option ? "selected='selected'" : "")."> $cur_option </option>";
                            }
                        ?>
                    </select>
        <?php
        }
        
        $address_vars = array(
        array(  'element_name' => 'firstName', 'title' => 'First Name', 'validation' => 'text',),
        array(  'element_name' => 'lastName',   'title' => 'Last Name', 'validation' => 'text',),
        array(  'element_name' => 'email', 'title' => 'Email Address', 'validation' => 'text',),
        array(  'element_name' => 'phone', 'title' => 'Phone Number', 'validation' => 'text',),
        array(  'element_name' => 'address', 'title' => 'Address', 'validation' => 'text',),
        array(  'element_name' => 'city', 'title' => 'City', 'validation' => 'text',),
        array(  'element_name' => 'state', 'title' => 'State', 'validation' => 'text',),
        array(  'element_name' => 'zip', 'title' => 'Zip Code', 'validation' => 'text',),
        );
    
        ?>
        <form>
        <?php
        foreach($address_vars as $cur_address_field) {
        ?>
    
            <label><?php echo $cur_address_field['title']; ?>: 
                <input 
                type = "text" 
                value="<?php echo (isset($_POST[$cur_address_field['element_name']]) ? $_POST[$cur_address_field['element_name']] : ''); ?>" 
                id = "<?php echo $cur_address_field['element_name']; ?>" 
                placeholder = "<?php echo $cur_address_field['title']; ?>" 
                name ="<?php echo $cur_address_field['element_name']; ?>">  
            </label>
            <?php } ?>
                <input type="reset"  class="buttons">
                <input type="submit" "submit-button" class="buttons">
            </form>
        <?php
    
            
        foreach($address_vars as $validate_field) {
            if($validate_field['validation'] == 'text') {
                // this is a text-based field, so we check it against the text-only regex
                $string_exp = "/^[A-Za-z .'-] $/";
                if(!preg_match($string_exp, $_POST[$validate_field['element_name']])) {
                    $message .= '<li>Please enter a ' . strtolower($validate_field['title']) . ' containing letters and spaces only.</li>';
                }
            } elseif($validate_field['validation'] == 'email') {
                $email_exp = '/^[A-Za-z0-9._%-] @[A-Za-z0-9.-] \.[A-Za-z]{2,4}$/';
                if(!preg_match($email_exp, $_POST[$validate_field['element_name']])) {
                    $message .= '<li>Please enter a valid ' . strtolower($validate_field['title']) . '.</li>';
                }
            }
        }
        ?>
        
    
    
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>T-Shirt Form</title>
            <link type="text/css" rel="stylesheet" href="css/style-prod.css">
            <script src="..js/script.js" defer></script>
        </head>
        <body>          
    
        
            <!--display processed information here-->
            <h3 class="subheaderone">Thank you for your order!</h3><br>
            <h3 class = "subheadertwo">Product:</h3>
            <div class = "output">
            
            <p><?php echo "value = '".$cur_option."' ".(isset($_POST[$cur_product['element_name']]) && $_POST[$cur_product['element_name']] == $cur_option ? "selected='selected'" : "")."> $cur_option";?>
            
            <h3 class = "subheadertwo">Shipping & Contact Information:</h3>
            <p>Name: <?php echo $_POST["firstName"]." ".$_POST["lastName"]; ?></p>
            <p>Email: <?php echo $_POST["email"]; ?></p>
            <p>Phone Number: <?php echo $_POST["phone"]; ?></p>
            <p>Address: </p>
            <p><?php echo $_POST["address"]; ?></p>
            <p><?php echo $_POST["city"].", ".$_POST["state"]." ".$_POST["zip"]; ?></p><br>
            </div>
            <div class="another"> 
            <nav><a href="./products.php"> Submit Another Form</a></nav> 
             </div> 
        </body>
    </html>

CodePudding user response:

Okay, so a few things here:

  • You don't need the variable assignations at the top. This is something very important in C and other languages, but PHP doesn't require this.

  • Your if(isset($_GET['firstName'])) $firstName = $_GET['firstName']; statements are using $_GET while your <form> tag uses $_POST - that's your main issue

  • I would recommend using an array of variables, something like this:

     $address_vars = array(
      array(
         'element_name' => 'firstName',
         'title' => 'First Name',
         'validation' => 'text',
      ),
      array(
         'element_name' => 'lastName',
         'title' => 'Last Name',
         'validation' => 'text',
      ),
    );
    

Then you can output the fields programmatically like this:

foreach($address_vars as $cur_address_field) {
    ?>
        <label><?php echo $cur_address_field['title']; ?>: <input type = "text" value="<?php echo (isset($_POST[$cur_address_field['element_name']]) ? $_POST[$cur_address_field['element_name']] : ''); ?>" id = "<?php echo $cur_address_field['element_name']; ?>" placeholder = "<?php echo $cur_address_field['title']; ?>" name ="<?php echo $cur_address_field['element_name']; ?>"></label>
    <?php
}

This not only cleans up the code quite a bit, but it also makes it much, much easier (and safer) to change/update or even add to the fields.

Then, to validate the fields you can use the validation array key I set up as a switch to go through all your fields. Something like this:

foreach($address_vars as $validate_field) {
    if($validate_field['validation'] == 'text') {
        // this is a text-based field, so we check it against the text-only regex
        $string_exp = "/^[A-Za-z .'-] $/";
        if(!preg_match($string_exp, $_POST[$validate_field['element_name']])) {
            $message .= '<li>Please enter a ' . strtolower($validate_field['title']) . ' containing letters and spaces only.</li>';
        }
    } elseif($validate_field['validation'] == 'email') {
        $email_exp = '/^[A-Za-z0-9._%-] @[A-Za-z0-9.-] \.[A-Za-z]{2,4}$/';
        if(!preg_match($email_exp, $_POST[$validate_field['element_name']])) {
            $message .= '<li>Please enter a valid ' . strtolower($validate_field['title']) . '.</li>';
        }
    }
}
  • You didn't wire up your product fields correctly. There's no way for the user-submitted value to 'stick' here, so the field's value is simply lost. To begin with, we can put these all in an array, similar to what we did with the address fields:

    $product_vars = array( array( 'element_name' => 'band', 'title' => 'Band', 'options' => $bands, 'placeholder' => 'Choose One', ), array( 'element_name' => 'color', 'title' => 'Color', 'options' => $colors, 'placeholder' => 'Choose One', ), );

Then we can use the following for the form:

foreach($product_vars as $cur_product) {
    ?>
            <label><?php echo $cur_product['title']; ?>: </label>
                <select name="<?php echo $cur_product['element_name']; ?>" size="1">
                    <option><?php echo $cur_product['placeholder']; ?></option>
                    <?php
                        foreach($cur_product['options'] as $cur_option)
                        {
                            echo "<option value = '".$cur_option."' ".(isset($_POST[$cur_product['element_name']]) && $_POST[$cur_product['element_name']] == $cur_option ? "selected='selected'" : "")."> $cur_option </option>";
                        }
                    ?>
                </select>
    <?php
}

Hopefully this helps!

**EDIT DUE TO NEW CODE SHARED **

There were again a few things here. Main items were: the $product_vars foreach being outside the <form> tag, the <form> tag not being set to use $_POST despite the rest of the code being set that way, and not adding any validation types. I've pasted the full code I have, which is working for me.

<?php
        //arrays
        $bands = array ("ACDC", "Journey", "Modest Mouse", "Band of Horses", "Vampire Weekend", "Of Monsters and Men", "Broken Bells", "Phoenix", "Fleetwood Mac", "AJR",);
        $colors = array ("Black", "Navy", "Red", "Orange", "Pink", "Yellow", "Green", "Gray", "White", "Purple",);
        $sizes = array ("X-Small", "Small", "Medium", "Large", "X-Large", "XX-Large", "XXX-Large",);
        $styles = array ("Tank Top", "T-Shirt", "Long Sleeve", "Hoodie", "Sweatshirt", "Jacket",);
        
        $product_vars = array(
        array( 'element_name' => 'band', 'title' => 'Band', 'options' => $bands, 'placeholder' => 'Choose One', ), 
        array( 'element_name' => 'color', 'title' => 'Color', 'options' => $colors, 'placeholder' => 'Choose One', ), 
        array( 'element_name' => 'size', 'title' => 'Size', 'options' => $sizes, 'placeholder' => 'Choose One', ), 
        array( 'element_name' => 'style', 'title' => 'Style', 'options' => $styles, 'placeholder' => 'Choose One', ), 
        );
    
        $address_vars = array(
        array(  'element_name' => 'firstName', 'title' => 'First Name', 'validation' => 'text',),
        array(  'element_name' => 'lastName',   'title' => 'Last Name', 'validation' => 'text',),
        array(  'element_name' => 'email', 'title' => 'Email Address', 'validation' => 'email',),
        array(  'element_name' => 'phone', 'title' => 'Phone Number', 'validation' => 'phone',),
        array(  'element_name' => 'address', 'title' => 'Address', 'validation' => 'address',),
        array(  'element_name' => 'city', 'title' => 'City', 'validation' => 'text',),
        array(  'element_name' => 'state', 'title' => 'State', 'validation' => 'text',),
        array(  'element_name' => 'zip', 'title' => 'Zip Code', 'validation' => 'zip',),
        );
    
        ?>
        <form action="" method="post">
        <?php
        foreach($product_vars as $cur_product) {
        ?>
                <label><?php echo $cur_product['title']; ?>: </label>
                    <select name="<?php echo $cur_product['element_name']; ?>" size="1">
                        <option><?php echo $cur_product['placeholder']; ?></option>
                        <?php
                            foreach($cur_product['options'] as $cur_option)
                            {
                                echo "<option value = '".$cur_option."' ".(isset($_POST[$cur_product['element_name']]) && $_POST[$cur_product['element_name']] == $cur_option ? "selected='selected'" : "")."> $cur_option </option>";
                            }
                        ?>
                    </select>
        <?php
        }
        foreach($address_vars as $cur_address_field) {
        ?>
    
            <label><?php echo $cur_address_field['title']; ?>: 
                <input 
                type = "text" 
                value="<?php echo (isset($_POST[$cur_address_field['element_name']]) ? $_POST[$cur_address_field['element_name']] : ''); ?>" 
                id = "<?php echo $cur_address_field['element_name']; ?>" 
                placeholder = "<?php echo $cur_address_field['title']; ?>" 
                name ="<?php echo $cur_address_field['element_name']; ?>">  
            </label>
            <?php } ?>
                <input type="reset" class="buttons">
                <input type="submit" class="buttons">
            </form>
        <?php


        foreach($address_vars as $validate_field) {
            $message = validate_field_contents($_POST[$validate_field['element_name']], $validate_field['title'], $validate_field['validation'], $message);
        }
        ?>
    
    
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>T-Shirt Form</title>
            <link type="text/css" rel="stylesheet" href="css/style-prod.css">
            <script src="..js/script.js" defer></script>
        </head>
        <body>          
    
            <?php
            if($message) {
                echo '<p>'.$message.'</p>';
            } else {
            ?>

            <!--display processed information here-->
            <h3 class="subheaderone">Thank you for your order!</h3><br>
            <h3 class = "subheadertwo">Product:</h3>
            <div class = "output">
            
                <h3 class = "subheadertwo">Shipping & Contact Information:</h3>
                <?php foreach($address_vars as $cur_address) {
                    echo '<p>' . $cur_address['title'] . ': ' . (isset($_POST[$cur_address['element_name']]) ? $_POST[$cur_address['element_name']] : '') . '</p>';
                } ?>
            </div>
            <div class="another"> 
                <nav><a href="./products.php"> Submit Another Form</a></nav> 
            </div>
            <?php } ?>
        </body>
    </html>


<?php

function validate_field_contents($content, $title, $type, $message) {
    if($type == 'text') {
        // this is a text-based field, so we check it against the text-only regex
        $string_exp = "/^[A-Za-z .'-] $/";
        if(!preg_match($string_exp, $content)) {
            $message .= '<li>Please enter a valid ' . strtolower($title) . ' containing letters and spaces only.</li>';
        }
    } elseif($type == 'email') {
        $email_exp = '/^[A-Za-z0-9._%-] @[A-Za-z0-9.-] \.[A-Za-z]{2,4}$/';
        if(!preg_match($email_exp, $content)) {
            $message .= '<li>Please enter a valid ' . strtolower($title) . '.</li>';
        }
    }
    return $message;
}
  • Related