表单处理 php

Form Processing php

我是新来的,所以如果我误解了如何在这里提交问题,请指出正确的方向。

1. 我收到警告错误,指出我有“未定义的数组键”。我在提交表格之前和之后都得到了这个。我已经在顶部定义了数组,所以我不确定为什么它们未定义。

2. 如果我输入不正确的 phone 数字格式,我的错误捕获将不起作用。我一开始收到错误提示,指出要将其置于正确的格式中,但如果我将信息置于正确的格式中并提交,我仍然收到错误消息,并且 phone 数字重置为最初的状态。我知道它是从 $_GET 中提取它,但不确定为什么当它再次提交时它没有更新 $_GET 以正确填充它。


<?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;
}
?>

好的,这里有几件事:

  • 您不需要顶部的变量赋值。这在 C 和其他语言中非常重要,但是 PHP 不需要这个。

  • 您的 if(isset($_GET['firstName'])) $firstName = $_GET['firstName']; 语句使用 $_GET 而您的 <form> 标签使用 $_POST - 这是您的主要问题

  • 我建议使用变量数组,如下所示:

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

然后您可以像这样以编程方式输出字段:

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
}

这不仅大大清理了代码,而且还使 change/update 甚至添加到字段中变得非常非常容易(也更安全)。

然后,要验证字段,您可以使用我设置为开关的 validation 数组键来遍历所有字段。像这样:

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>';
        }
    }
}
  • 您没有正确连接您的产品字段。这里无法将用户提交的值设为 'stick',因此该字段的值将丢失。首先,我们可以将这些都放在一个数组中,类似于我们对地址字段所做的:

    $product_vars = 数组( 大批( 'element_name' => 'band', 'title' => 'Band', 'options' => $bands, 'placeholder' => 'Choose One', ), 大批( 'element_name' => 'color', 'title' => 'Color', 'options' => $颜色, '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
}

希望这对您有所帮助!

**由于共享了新代码而进行了编辑**

这里又发生了一些事情。主要项目是:$product_vars foreach 在 <form> 标签之外,<form> 标签没有被设置为使用 $_POST 尽管代码的其余部分是这样设置的,并且不添加任何验证类型。我已经粘贴了我拥有的完整代码,这对我有用。

<?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;
}