Home > database >  Form Processing php
Form Processing php

Time:10-22

I am new here so please point me in the right direction if I am misunderstanding how to submit a question here.

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. 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.


<?php

function validate_field_contents($content, $title, $type, $message, ) {
    if($type == 'text') {
        $string_exp = "/^[A-Za-z0-9._%-]/";
        if(!preg_match($string_exp, $content)) {
            $message .= '<li>Please enter a valid ' . strtolower($title) . '.</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>';
        }
    }
    elseif($type == 'phone'){
        $num_exp = "/^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$/";
         if(!preg_match($num_exp,$content)) {
             {$message .= '<li>Please enter a valid ' . strtolower($title) . ' in the following format (xxx)xxx-xxxx.</li>';}
        }
    }
    elseif($type == 'zip'){
        $num_exp = "/^[0-9]{5}$/";
         if(!preg_match($num_exp,$content)) {
             {$message .= '<li>Please enter a valid ' . strtolower($title) . ' with 5 numbers only.</li>';}
        }
    }
    elseif(empty($_POST['band'])){
            {$message .= '<li>Please select a ' . strtolower($title) . '.</li>';}
    }
    elseif(empty($type == 'color')){
         $message .= '<li>Please select a ' . strtolower($title) . '.</li>';
        }
    elseif(empty($type == 'size')){
         $message .= '<li>Please select a ' . strtolower($title) . '.</li>';
        }
    elseif(empty($type == 'style')){
         $message .= '<li>Please select a ' . strtolower($title) . '.</li>';
        }
    return $message;
}
?>

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